﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using PMisuseAn.io;
using PMisuseAn.behaviour.model;
using System.IO;
using System.Collections;
using System.Collections.ObjectModel;
using Microsoft.Msagl.Drawing;
using Microsoft.Msagl.GraphViewerGdi;
using PMisuseAn.util;

namespace PMisuseAn
{
    /// <summary>
    /// Interaction logic for AddStateMachineWindow.xaml
    /// </summary>
    public partial class AddStateMachineWindow : Window
    {
        ContextInterface ci_;
        string machineName_;
        string stateName_;
        StateMachine machine_;
        bool isEventUpdate = false;
        bool isStateUpdate = false;
        bool isStateActionUpdate = false;
        //bool isStateTransitionUpdate = false;
        bool loadingTriggers = false;
        bool isStateActionSelection = false;
        bool isStateSelection = false;
        bool isEventSelection = false;
        bool isTransitionSelection = false;
        bool isTransitionRootSelection = false;
        bool isStateRootSelection = false;
        bool isEventRootSelection = false;

        string startState;
        string endState;

        Event newEvent;
        State newState;
        Transition newStateTransition;
        PMisuseAn.behaviour.model.Action newAction;
        List<Event> allExisitngEvents;
        List<State> allExistingStates;
        List<Transition> allExistingStateTransitions;
        List<PMisuseAn.behaviour.model.Action> allExistingStateActions;

        List<Attribute> agentAttributes;
        //List<Attribute> functionalAttributes;
        List<Attribute> environmentalAttributes;

        TreeViewItem stateActionSelected_tv;
        Graph glee_fsm_graph;
        GViewer viewer = new GViewer();

        public AddStateMachineWindow(ContextInterface ci, StateMachine machine)
        {
            InitializeComponent();
            this.Left = 20;
            this.Top = 25;

            ci_ = ci;
            machine_ = machine;
            machineName_ = machine.machineName;
            state_machine_root.Header = machineName_; 

            loadEvents(machine);
            loadStates(machine);
            loadTransitions(machine);
            
            agentAttributes = new List<Attribute>();
            //functionalAttributes = new List<Attribute>();
            environmentalAttributes = new List<Attribute>();
            
            new_ent_name_tb.Visibility = System.Windows.Visibility.Hidden;
            new_ent_Name_l.Visibility = System.Windows.Visibility.Hidden;
            apply_new_event_b.Visibility = System.Windows.Visibility.Hidden;
            new_ent_desc_tb.Visibility = System.Windows.Visibility.Hidden;
            new_event_ppties_gb.Visibility = System.Windows.Visibility.Hidden;
            desc_l.Visibility = System.Windows.Visibility.Hidden;
            update_event_b.Visibility = System.Windows.Visibility.Hidden;
            delete_event_b.Visibility = System.Windows.Visibility.Hidden;
            define_state_b.Visibility = System.Windows.Visibility.Hidden;
            update_state_b.Visibility = System.Windows.Visibility.Hidden;
            delete_state_b.Visibility = System.Windows.Visibility.Hidden;
            operational_atts_gb.Visibility = System.Windows.Visibility.Hidden;
            state_action_apply_b.Visibility = System.Windows.Visibility.Hidden;
            state_action_update_b.Visibility = System.Windows.Visibility.Hidden;
            state_action_delete_b.Visibility = System.Windows.Visibility.Hidden;
            transitionPolicies_gb.Visibility = System.Windows.Visibility.Hidden;
            apply_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            update_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            start_state_l.Visibility = System.Windows.Visibility.Hidden;
            start_state_cb.Visibility = System.Windows.Visibility.Hidden;
            ass_event_l.Visibility = System.Windows.Visibility.Hidden;
            associated_event_cb.Visibility = System.Windows.Visibility.Hidden;
            end_state_l.Visibility = System.Windows.Visibility.Hidden;
            end_state_cb.Visibility = System.Windows.Visibility.Hidden;
            delete_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            isCallableState_cb.Visibility = System.Windows.Visibility.Hidden;
            isCallableTransition_cb.Visibility = System.Windows.Visibility.Hidden;
            
            genStateMachineGraph();
        }

        public AddStateMachineWindow(ContextInterface ci, string machineName)
        {
            InitializeComponent();
            this.Left = 20;
            this.Top = 25;

            ci_ = ci;
            machineName_ = machineName;
            machine_ = new StateMachine();
            machine_.machineName = machineName_;

            state_machine_root.Header = machineName_;
            loadEvents();
            loadStates();
            loadTransitions();

            agentAttributes = new List<Attribute>();
            //functionalAttributes = new List<Attribute>();
            environmentalAttributes = new List<Attribute>();

            new_ent_name_tb.Visibility = System.Windows.Visibility.Hidden;
            new_ent_Name_l.Visibility = System.Windows.Visibility.Hidden;
            apply_new_event_b.Visibility = System.Windows.Visibility.Hidden;
            new_ent_desc_tb.Visibility = System.Windows.Visibility.Hidden;
            new_event_ppties_gb.Visibility = System.Windows.Visibility.Hidden;
            desc_l.Visibility = System.Windows.Visibility.Hidden;
            update_event_b.Visibility = System.Windows.Visibility.Hidden;
            delete_event_b.Visibility = System.Windows.Visibility.Hidden;
            define_state_b.Visibility = System.Windows.Visibility.Hidden;
            delete_state_b.Visibility = System.Windows.Visibility.Hidden;
            update_state_b.Visibility = System.Windows.Visibility.Hidden;
            operational_atts_gb.Visibility = System.Windows.Visibility.Hidden;
            state_action_apply_b.Visibility = System.Windows.Visibility.Hidden;
            state_action_update_b.Visibility = System.Windows.Visibility.Hidden;
            state_action_delete_b.Visibility = System.Windows.Visibility.Hidden;
            transitionPolicies_gb.Visibility = System.Windows.Visibility.Hidden;
            apply_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            update_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            start_state_l.Visibility = System.Windows.Visibility.Hidden;
            start_state_cb.Visibility = System.Windows.Visibility.Hidden;
            ass_event_l.Visibility = System.Windows.Visibility.Hidden;
            associated_event_cb.Visibility = System.Windows.Visibility.Hidden;
            end_state_l.Visibility = System.Windows.Visibility.Hidden;
            end_state_cb.Visibility = System.Windows.Visibility.Hidden;
            delete_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            isCallableState_cb.Visibility = System.Windows.Visibility.Hidden;
            isCallableTransition_cb.Visibility = System.Windows.Visibility.Hidden;

        }

        private void state_machine_root_TreeViewItem_Selected(object sender, RoutedEventArgs e)
        {
            TreeViewItem d_cb = (TreeViewItem)sender;
            string tag_id = (string)d_cb.Tag;
            
            if (isStateActionSelection == false && isStateSelection == false
                && isTransitionSelection == false && isEventSelection == false
                && isEventRootSelection == false && isStateRootSelection == false
                && isTransitionRootSelection == false)
            {
                if (tag_id.Equals("root"))
                {
                    new_ent_name_tb.Visibility = System.Windows.Visibility.Hidden;
                    new_ent_Name_l.Visibility = System.Windows.Visibility.Hidden;
                    apply_new_event_b.Visibility = System.Windows.Visibility.Hidden;
                    new_ent_desc_tb.Visibility = System.Windows.Visibility.Hidden;
                    new_event_ppties_gb.Visibility = System.Windows.Visibility.Hidden;
                    desc_l.Visibility = System.Windows.Visibility.Hidden;
                    update_event_b.Visibility = System.Windows.Visibility.Hidden;
                    delete_event_b.Visibility = System.Windows.Visibility.Hidden;
                    define_state_b.Visibility = System.Windows.Visibility.Hidden;
                    delete_state_b.Visibility = System.Windows.Visibility.Hidden;
                    update_state_b.Visibility = System.Windows.Visibility.Hidden;
                    operational_atts_gb.Visibility = System.Windows.Visibility.Hidden;
                    state_action_apply_b.Visibility = System.Windows.Visibility.Hidden;
                    state_action_update_b.Visibility = System.Windows.Visibility.Hidden;
                    state_action_delete_b.Visibility = System.Windows.Visibility.Hidden;
                    transitionPolicies_gb.Visibility = System.Windows.Visibility.Hidden;
                    update_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
                    apply_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
                    start_state_l.Visibility = System.Windows.Visibility.Hidden;
                    start_state_cb.Visibility = System.Windows.Visibility.Hidden;
                    ass_event_l.Visibility = System.Windows.Visibility.Hidden;
                    associated_event_cb.Visibility = System.Windows.Visibility.Hidden;
                    end_state_l.Visibility = System.Windows.Visibility.Hidden;
                    end_state_cb.Visibility = System.Windows.Visibility.Hidden;
                    delete_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
                    isCallableState_cb.Visibility = System.Windows.Visibility.Hidden;
                    isCallableTransition_cb.Visibility = System.Windows.Visibility.Hidden;
                } 
            }

            else
            {
                isStateActionSelection = false;
                isStateSelection = false;
                isEventSelection = false;
                isTransitionSelection = false;
                isTransitionRootSelection = false;
                isStateRootSelection = false;
                isEventRootSelection = false;
            }           
        }
        private void events_root_TreeViewItem_Selected(object sender, RoutedEventArgs e)
        {
            isEventRootSelection = true;
        }
        private void states_root_TreeViewItem_Selected(object sender, RoutedEventArgs e)
        {
            isStateRootSelection = true;
        }
        private void transitions_root_TreeViewItem_Selected(object sender, RoutedEventArgs e)
        {
            isTransitionRootSelection = true;
        }

        private void event_TreeViewItem_Selected(object sender, RoutedEventArgs e)
        {
            isEventSelection = true;

            TreeViewItem d_cb = (TreeViewItem)sender;
            string tag_id = (string)d_cb.Tag;
            if (tag_id.Equals(""))
            {
                isEventUpdate = false;
               // allExisitngEvents = MisUseAnObjectsDB.loadAllEvents(machineName_, MainWindow.clusterName);
                allExisitngEvents = machine_.events;
                newEvent = new Event();
                newEvent.machineName = machineName_;
                newEvent.clusterName = MainWindow.clusterName;
                new_ent_name_tb.Text = "";
                new_ent_name_tb.IsReadOnly = false;
                new_ent_desc_tb.Text = "";
                loadAttributesToEventOperationalAttributes();

                loadingTriggers = true;
                time_event_cb.IsChecked = false;
                call_event_cb.IsChecked = false;
                signal_event_cb.IsChecked = false;
                change_event_cb.IsChecked = false;
                loadingTriggers = false;
               
                apply_new_event_b.Visibility = System.Windows.Visibility.Visible;
                update_event_b.Visibility = System.Windows.Visibility.Hidden;
                delete_event_b.Visibility = System.Windows.Visibility.Hidden;
            }
            else
            {
                newEvent = MisUseAnObjectsDB.loadEventDB(tag_id, machineName_, MainWindow.clusterName);
                if (newEvent != null)
                {
                    isEventUpdate = true;
                    new_ent_name_tb.Text = newEvent.name;
                    new_ent_name_tb.IsReadOnly = true;
                    new_ent_desc_tb.Text = newEvent.description;
                    reloadAttributesToEventOperationalAttributes(newEvent.operationalAttributes_);

                    if (newEvent.type.Equals("request"))
                    {
                        request_event_rb.IsChecked = true;
                    }
                    else
                    {
                        response_event_rb.IsChecked = true;
                    }

                    loadingTriggers = true;
                    time_event_cb.IsChecked = false;
                    call_event_cb.IsChecked = false;
                    signal_event_cb.IsChecked = false;
                    change_event_cb.IsChecked = false;
                    foreach (string trigger in newEvent.triggers)
                    {
                        if (trigger.Equals("timed"))
                        {
                            time_event_cb.IsChecked = true;
                        }
                        else if (trigger.Equals("call"))
                        {
                            call_event_cb.IsChecked = true;
                        }
                        else if (trigger.Equals("signal"))
                        {
                            signal_event_cb.IsChecked = true;
                        }
                        else if (trigger.Equals("change"))
                        {
                            change_event_cb.IsChecked = true;
                        }
                    }
                    loadingTriggers = false;
                  
                    apply_new_event_b.Visibility = System.Windows.Visibility.Hidden;
                    update_event_b.Visibility = System.Windows.Visibility.Visible;
                    delete_event_b.Visibility = System.Windows.Visibility.Visible;
                }
            }
            new_ent_name_tb.Visibility = System.Windows.Visibility.Visible;
            new_ent_Name_l.Visibility = System.Windows.Visibility.Visible;            
            new_ent_desc_tb.Visibility = System.Windows.Visibility.Visible;
            new_event_ppties_gb.Visibility = System.Windows.Visibility.Visible;
            desc_l.Visibility = System.Windows.Visibility.Visible;
            define_state_b.Visibility = System.Windows.Visibility.Hidden;
            update_state_b.Visibility = System.Windows.Visibility.Hidden;
            delete_state_b.Visibility = System.Windows.Visibility.Hidden;
            operational_atts_gb.Visibility = System.Windows.Visibility.Visible;
            state_action_apply_b.Visibility = System.Windows.Visibility.Hidden;
            state_action_update_b.Visibility = System.Windows.Visibility.Hidden;
            state_action_delete_b.Visibility = System.Windows.Visibility.Hidden;
            transitionPolicies_gb.Visibility = System.Windows.Visibility.Hidden;
            update_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            apply_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            start_state_l.Visibility = System.Windows.Visibility.Hidden;
            start_state_cb.Visibility = System.Windows.Visibility.Hidden;
            ass_event_l.Visibility = System.Windows.Visibility.Hidden;
            associated_event_cb.Visibility = System.Windows.Visibility.Hidden;
            end_state_l.Visibility = System.Windows.Visibility.Hidden;
            end_state_cb.Visibility = System.Windows.Visibility.Hidden;
            delete_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            isCallableState_cb.Visibility = System.Windows.Visibility.Hidden;
            isCallableTransition_cb.Visibility = System.Windows.Visibility.Hidden;

        }

        private void transition_TreeViewItem_Selected(object sender, RoutedEventArgs e)
        {
            isTransitionSelection = true;

            TreeViewItem d_cb = (TreeViewItem)sender;
            string tag_id = (string)d_cb.Tag;
            reloadEntsInComboBox();

            if (tag_id.Equals("new"))
            {
                newStateTransition = new Transition();
                newStateTransition.machineName = machineName_;
                newStateTransition.clusterName = MainWindow.clusterName;
                //isStateTransitionUpdate = false;

                new_ent_name_tb.Text = "";
                new_ent_name_tb.IsReadOnly = false;
                start_state_cb.Text = "";
                start_state_cb.IsEnabled = true;
                end_state_cb.Text = "";
                end_state_cb.IsEnabled = true;
                associated_event_cb.Text = "";
                associated_event_cb.IsEnabled = true;
                loadStateTransitionsPolicyStatementList(newStateTransition);

                apply_new_state_transition_b.Visibility = System.Windows.Visibility.Visible;
                update_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
                delete_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            }
            else
            {
                string[] tag_comps = tag_id.Split(',');
                string transitionName_t = tag_comps[0];
                string machineName_t = tag_comps[1];
                string startState_t = tag_comps[2];
                string endState_t = tag_comps[3];
                string associatedEvent_t = tag_comps[4];

                //newStateTransition = MisUseAnObjectsDB.loadStateTransitionDB(machineName_t,
                //    transitionName_t, startState_t, endState_t, associatedEvent_t, MainWindow.clusterName);
                newStateTransition = machine_.getStateTransition(transitionName_t, startState_t, endState_t, associatedEvent_t);
                //isStateTransitionUpdate = true;
               
                new_ent_name_tb.Text = transitionName_t;
                new_ent_name_tb.IsReadOnly = true;
                start_state_cb.Text = startState_t;
                start_state_cb.IsEnabled = false;
                end_state_cb.Text = endState_t;
                end_state_cb.IsEnabled = false;
                associated_event_cb.Text = associatedEvent_t;
                associated_event_cb.IsEnabled = false;
                if (newStateTransition != null && newStateTransition.isCallable)
                {
                    isCallableTransition_cb.IsChecked = true;
                }
                else
                {
                    isCallableTransition_cb.IsChecked = false;
                }
                if (newStateTransition != null && newStateTransition.policyIDs != null)
                     reloadStateTransitionsPolicyStatementList(newStateTransition);
                   //reloadStateTransitionsPolicyStatementList(newStateTransition.policyIDs);

                apply_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
                update_new_state_transition_b.Visibility = System.Windows.Visibility.Visible;
                delete_state_transition_b.Visibility = System.Windows.Visibility.Visible;
            }            

            new_ent_name_tb.Visibility = System.Windows.Visibility.Visible;
            new_ent_Name_l.Visibility = System.Windows.Visibility.Visible;
            apply_new_event_b.Visibility = System.Windows.Visibility.Hidden;
            new_ent_desc_tb.Visibility = System.Windows.Visibility.Hidden;
            new_event_ppties_gb.Visibility = System.Windows.Visibility.Hidden;
            desc_l.Visibility = System.Windows.Visibility.Hidden;
            update_event_b.Visibility = System.Windows.Visibility.Hidden;
            delete_event_b.Visibility = System.Windows.Visibility.Hidden;
            define_state_b.Visibility = System.Windows.Visibility.Hidden;
            delete_state_b.Visibility = System.Windows.Visibility.Hidden;
            update_state_b.Visibility = System.Windows.Visibility.Hidden;
            operational_atts_gb.Visibility = System.Windows.Visibility.Hidden;
            state_action_apply_b.Visibility = System.Windows.Visibility.Hidden;
            state_action_update_b.Visibility = System.Windows.Visibility.Hidden;
            state_action_delete_b.Visibility = System.Windows.Visibility.Hidden;
            transitionPolicies_gb.Visibility = System.Windows.Visibility.Visible;
            start_state_l.Visibility = System.Windows.Visibility.Visible;
            start_state_cb.Visibility = System.Windows.Visibility.Visible;
            ass_event_l.Visibility = System.Windows.Visibility.Visible;
            associated_event_cb.Visibility = System.Windows.Visibility.Visible;
            end_state_l.Visibility = System.Windows.Visibility.Visible;
            end_state_cb.Visibility = System.Windows.Visibility.Visible;
            isCallableState_cb.Visibility = System.Windows.Visibility.Hidden;
            isCallableTransition_cb.Visibility = System.Windows.Visibility.Visible;
        }

        private void state_action_TreeViewItem_Selected(object sender, RoutedEventArgs e)
        {
            isStateActionSelection = true;
            TreeViewItem d_cb = (TreeViewItem)sender;

            string tag_id = (string)d_cb.Tag;
            string [] tag_split = tag_id.Split(',');

            string actionName = tag_split[0];
            string stateName = tag_split[1];
            stateName_ = stateName;

            if (actionName.Equals("new"))
            {
                isStateActionUpdate = false;
                //allExistingStateActions = MisUseAnObjectsDB.loadAllStateActions(machineName_, stateName);
                newAction = new PMisuseAn.behaviour.model.Action();
                loadAttributesToStateActionOperationalAttributes();
                newAction.machineName = machineName_;
                newAction.stateName = stateName;
                newAction.clusterName = MainWindow.clusterName;
                new_ent_name_tb.Text = "";
                new_ent_name_tb.IsReadOnly = false;
                new_ent_desc_tb.Text = "";

                state_action_apply_b.Visibility = System.Windows.Visibility.Visible;
                state_action_update_b.Visibility = System.Windows.Visibility.Hidden;
                state_action_delete_b.Visibility = System.Windows.Visibility.Hidden;
            }
            else
            {
                isStateActionUpdate = true;
                //newAction = MisUseAnObjectsDB.loadStateActionDB(actionName, stateName, machineName_, MainWindow.clusterName);
                newAction = machine_.getStateAction(actionName, stateName);
                if (newAction != null)
                {
                    reloadAttributesToStateActionOperationalAttributes(newAction.operationalAttributes_);
                    new_ent_name_tb.Text = newAction.name;
                    new_ent_name_tb.IsReadOnly = true;
                    new_ent_desc_tb.Text = newAction.description;

                    state_action_apply_b.Visibility = System.Windows.Visibility.Hidden;
                    state_action_update_b.Visibility = System.Windows.Visibility.Visible;
                    state_action_delete_b.Visibility = System.Windows.Visibility.Visible;
                }

            }
            new_ent_name_tb.Visibility = System.Windows.Visibility.Visible;
            new_ent_Name_l.Visibility = System.Windows.Visibility.Visible;
            apply_new_event_b.Visibility = System.Windows.Visibility.Hidden;
            new_ent_desc_tb.Visibility = System.Windows.Visibility.Visible;
            new_event_ppties_gb.Visibility = System.Windows.Visibility.Hidden;
            desc_l.Visibility = System.Windows.Visibility.Visible;
            update_event_b.Visibility = System.Windows.Visibility.Hidden;
            delete_event_b.Visibility = System.Windows.Visibility.Hidden;
            define_state_b.Visibility = System.Windows.Visibility.Hidden;
            delete_state_b.Visibility = System.Windows.Visibility.Hidden;
            update_state_b.Visibility = System.Windows.Visibility.Hidden;
            operational_atts_gb.Visibility = System.Windows.Visibility.Visible;
            transitionPolicies_gb.Visibility = System.Windows.Visibility.Hidden;
            update_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            apply_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            start_state_l.Visibility = System.Windows.Visibility.Hidden;
            start_state_cb.Visibility = System.Windows.Visibility.Hidden;
            ass_event_l.Visibility = System.Windows.Visibility.Hidden;
            associated_event_cb.Visibility = System.Windows.Visibility.Hidden;
            end_state_l.Visibility = System.Windows.Visibility.Hidden;
            end_state_cb.Visibility = System.Windows.Visibility.Hidden;
            delete_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            isCallableState_cb.Visibility = System.Windows.Visibility.Hidden;
            isCallableTransition_cb.Visibility = System.Windows.Visibility.Hidden;
        }
        
        private void state_TreeViewItem_Selected(object sender, RoutedEventArgs e)
        {
            TreeViewItem d_cb = (TreeViewItem)sender;
            stateActionSelected_tv = d_cb;

            isStateSelection = true;

            if (isStateActionSelection == false)
            {
                string tag_id = (string)d_cb.Tag;
                if (tag_id.Equals(""))
                {
                    isStateUpdate = false;
                    //allExistingStates = MisUseAnObjectsDB.loadAllStates(machineName_, MainWindow.clusterName);
                    allExistingStates = machine_.states;
                    newState = new State();
                    newState.machineName = machineName_;
                    newState.clusterName = MainWindow.clusterName;
                    new_ent_name_tb.Text = "";
                    new_ent_name_tb.IsReadOnly = false;
                    new_ent_desc_tb.Text = "";

                    define_state_b.Visibility = System.Windows.Visibility.Visible;
                    delete_state_b.Visibility = System.Windows.Visibility.Hidden;
                    update_state_b.Visibility = System.Windows.Visibility.Hidden;
                }
                else
                {
                    //newState = MisUseAnObjectsDB.loadStateDB(tag_id, machineName_, MainWindow.clusterName);
                    newState = machine_.getStateX(tag_id);
                    if (newState != null)
                    {
                        isStateUpdate = true;
                        new_ent_name_tb.Text = newState.name;
                        new_ent_name_tb.IsReadOnly = true;
                        new_ent_desc_tb.Text = newState.description;

                        if (newState.isCallable)
                        {
                            isCallableState_cb.IsChecked = true;
                        }
                        else
                        {
                            isCallableState_cb.IsChecked = false;
                        }
                        define_state_b.Visibility = System.Windows.Visibility.Hidden;
                        delete_state_b.Visibility = System.Windows.Visibility.Visible;
                        update_state_b.Visibility = System.Windows.Visibility.Visible;
                    }
                }
                new_ent_name_tb.Visibility = System.Windows.Visibility.Visible;
                new_ent_Name_l.Visibility = System.Windows.Visibility.Visible;
                apply_new_event_b.Visibility = System.Windows.Visibility.Hidden;
                new_ent_desc_tb.Visibility = System.Windows.Visibility.Visible;
                new_event_ppties_gb.Visibility = System.Windows.Visibility.Hidden;
                desc_l.Visibility = System.Windows.Visibility.Visible;
                update_event_b.Visibility = System.Windows.Visibility.Hidden;
                delete_event_b.Visibility = System.Windows.Visibility.Hidden;
                operational_atts_gb.Visibility = System.Windows.Visibility.Hidden;
                state_action_apply_b.Visibility = System.Windows.Visibility.Hidden;
                state_action_update_b.Visibility = System.Windows.Visibility.Hidden;
                state_action_delete_b.Visibility = System.Windows.Visibility.Hidden;
                transitionPolicies_gb.Visibility = System.Windows.Visibility.Hidden;
                update_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
                apply_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
                start_state_l.Visibility = System.Windows.Visibility.Hidden;
                start_state_cb.Visibility = System.Windows.Visibility.Hidden;
                ass_event_l.Visibility = System.Windows.Visibility.Hidden;
                associated_event_cb.Visibility = System.Windows.Visibility.Hidden;
                end_state_l.Visibility = System.Windows.Visibility.Hidden;
                end_state_cb.Visibility = System.Windows.Visibility.Hidden;
                delete_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
                isCallableState_cb.Visibility = System.Windows.Visibility.Visible;
                isCallableTransition_cb.Visibility = System.Windows.Visibility.Hidden;
            }
            else
            {
                isStateActionSelection = false;
            }
        }
        
        private void loadEvents()
        {
            events.Items.Clear();

            TreeViewItem item_n = new TreeViewItem();
            item_n.Header = "New..     ";
            item_n.Tag = "";
            item_n.FontStyle = FontStyles.Italic;
            item_n.Foreground = Brushes.Blue;
            item_n.AddHandler(TreeViewItem.SelectedEvent, new RoutedEventHandler(event_TreeViewItem_Selected));
            events.Items.Add(item_n); 

            //allExisitngEvents = MisUseAnObjectsDB.loadAllEvents(machineName_, MainWindow.clusterName);
            allExisitngEvents = machine_.events;

            if(allExisitngEvents != null)
            foreach (Event eve in allExisitngEvents)
            {
                if (!events.Items.Contains(eve.name))
                {
                    TreeViewItem item = new TreeViewItem();
                    item.Header = eve.name;
                    item.Tag = eve.name;
                    item.AddHandler(TreeViewItem.SelectedEvent, new RoutedEventHandler(event_TreeViewItem_Selected));

                    //if (eve.isMitigationPoint == true)
                    //{
                    //    item.Background = Brushes.LightYellow;
                    //}
                    //if (eve.isMisusePoint == true)
                    //{
                    //    item.Background = Brushes.OrangeRed;
                    //}

                    //ContextMenu cm_event = new System.Windows.Controls.ContextMenu();
                    //cm_event.Height = 62;
                    //cm_event.Width = 130;

                    //MenuItem cm_mp_event = new MenuItem();
                    //cm_mp_event.Header = "mitigation point";
                    //cm_mp_event.Tag = eve.name;
                    //if (eve.isMitigationPoint == true)
                    //{
                    //    cm_mp_event.IsChecked = true;
                    //}
                    //cm_mp_event.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(mitigation_point_event_clicked));
                    //cm_mp_event.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(mitigation_point_event_clicked));
                    //cm_mp_event.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                    //cm_mp_event.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                    //cm_mp_event.FontSize = 10;
                    //cm_mp_event.Background = Brushes.LightYellow;
                    //cm_mp_event.IsCheckable = true;

                    //MenuItem cm_mu_event = new MenuItem();
                    //cm_mu_event.Header = "misuse point";
                    //cm_mu_event.Tag = eve.name;
                    //if (eve.isMisusePoint == true)
                    //{
                    //    cm_mu_event.IsChecked = true;
                    //}
                    //cm_mu_event.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(misuse_point_event_clicked));
                    //cm_mu_event.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(misuse_point_event_clicked));
                    //cm_mu_event.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                    //cm_mu_event.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                    //cm_mu_event.FontSize = 10;
                    //cm_mu_event.Background = Brushes.OrangeRed;
                    //cm_mu_event.IsCheckable = true;

                    //cm_event.Items.Add(cm_mp_event);
                    //cm_event.Items.Add(cm_mu_event);

                    //item.ContextMenu = cm_event;
                    
                    events.Items.Add(item);
                }
            }
        }

        private void loadStates()
        {
            
            states.Items.Clear();
            string startState = MisUseAnObjectsDB.getStartState(machineName_, MainWindow.clusterName);
            string endState = MisUseAnObjectsDB.getEndState(machineName_, MainWindow.clusterName);

            TreeViewItem item_n = new TreeViewItem();
            item_n.Header = "New..     ";
            item_n.Tag = "";
            item_n.FontStyle = FontStyles.Italic;
            item_n.Foreground = Brushes.Blue;
            item_n.AddHandler(TreeViewItem.SelectedEvent, new RoutedEventHandler(state_TreeViewItem_Selected));
            states.Items.Add(item_n);
            
            //allExistingStates = MisUseAnObjectsDB.loadAllStates(machineName_, MainWindow.clusterName);
            allExistingStates = machine_.states;
            if(allExistingStates !=null)
            foreach (State sta in allExistingStates)
            {
                if (!states.Items.Contains(sta.name))
                {
                    TreeViewItem item = new TreeViewItem();
                    item.Header = sta.name;
                    item.Tag = sta.name;
                    item.AddHandler(TreeViewItem.SelectedEvent, new RoutedEventHandler(state_TreeViewItem_Selected));
                    if (sta.name.Equals(startState))
                    {
                        item.Foreground = Brushes.DarkSeaGreen;
                    }
                    else if (sta.name.Equals(endState))
                    {
                        item.Foreground = Brushes.DarkRed;
                    }

                    //if (sta.isMitigationPoint == true)
                    //{
                    //    item.Background = Brushes.LightYellow;
                    //}
                    if (sta.isMisusePoint == true)
                    {
                        item.Background = Brushes.OrangeRed;
                    }

                    MitigationReferences m_ref_s = MisUseAnObjectsDB.loadStateMitigationReferencesDB(sta.name, machineName_, MainWindow.clusterName);

                    if (m_ref_s.isEmpty == false)
                    {
                        item.Background = Brushes.Green;
                    }

                    TreeViewItem item_action = new TreeViewItem();
                    item_action.Header = "New.. (action)";
                    item_action.FontStyle = FontStyles.Italic;
                    item_action.Foreground = Brushes.Blue;
                    item_action.Tag = "new," + sta.name;
                    item_action.AddHandler(TreeViewItem.SelectedEvent, new RoutedEventHandler(state_action_TreeViewItem_Selected));
                    item.Items.Add(item_action);
                    foreach (PMisuseAn.behaviour.model.Action action in sta.actions)
                    {
                        TreeViewItem item_act = new TreeViewItem();
                        item_act.Header = action.name;
                        item_act.Tag = action.name+"," + sta.name;
                        item_act.AddHandler(TreeViewItem.SelectedEvent, new RoutedEventHandler(state_action_TreeViewItem_Selected));

                        //if (action.isMitigationPoint == true)
                        //{
                        //    item_act.Background = Brushes.LightYellow;
                        //}
                        if (action.isMisusePoint == true)
                        {
                            item_act.Background = Brushes.OrangeRed;
                        }
                        MitigationReferences m_ref = MisUseAnObjectsDB.loadStateActionMitigationReferencesDB(action.name, sta.name, machineName_, MainWindow.clusterName);

                        if (m_ref.isEmpty == false)
                        {
                            item_act.Background = Brushes.Green;
                        }

                        ContextMenu cm_act = new System.Windows.Controls.ContextMenu();
                        cm_act.Height = 60;
                        cm_act.Width = 150;

                        //MenuItem cm_mp_act = new MenuItem();
                        //cm_mp_act.Header = "mitigation point";
                        //cm_mp_act.Tag = action.name+"," + sta.name;
                        //if (action.isMitigationPoint == true)
                        //{
                        //    cm_mp_act.IsChecked = true;
                        //}
                        //cm_mp_act.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(mitigation_point_state_action_clicked));
                        //cm_mp_act.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(mitigation_point_state_action_clicked));
                        //cm_mp_act.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                        //cm_mp_act.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                        //cm_mp_act.FontSize = 10;
                        //cm_mp_act.Background = Brushes.LightYellow;
                        //cm_mp_act.IsCheckable = true;

                        MenuItem cm_mu_act = new MenuItem();
                        cm_mu_act.Header = "misuse point";
                        cm_mu_act.Tag = action.name + "," + sta.name;
                        if (action.isMisusePoint == true)
                        {
                            cm_mu_act.IsChecked = true;
                        }
                        cm_mu_act.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(misuse_point_state_action_clicked));
                        cm_mu_act.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(misuse_point_state_action_clicked));
                        cm_mu_act.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                        cm_mu_act.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                        cm_mu_act.FontSize = 10;
                        //cm_mu_act.Background = Brushes.OrangeRed;
                        cm_mu_act.IsCheckable = true;

                        MenuItem cm_m_act = new MenuItem();
                        cm_m_act.Header = "Mitigation references";
                        cm_m_act.Tag = action.name + "," + sta.name;
                        if (action.isMisusePoint == false)
                        {
                            cm_m_act.IsEnabled = false;
                        }
                        if (m_ref.isEmpty == false)
                        {
                            cm_m_act.IsChecked = true;
                        }
                        cm_m_act.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(mitigation_references_state_action_clicked));
                        cm_m_act.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(mitigation_references_state_action_clicked));
                        cm_m_act.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                        cm_m_act.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                        cm_m_act.FontSize = 10;
                        //cm_m_act.Background = Brushes.OrangeRed;
                        cm_m_act.IsCheckable = true;

                        //cm_act.Items.Add(cm_mp_act);
                        cm_act.Items.Add(cm_mu_act);
                        cm_act.Items.Add(cm_m_act);

                        item_act.ContextMenu = cm_act;
                        item.Items.Add(item_act);

                        item.IsExpanded = true;
                    }

                    ContextMenu cm = new System.Windows.Controls.ContextMenu();
                    cm.Height = 110;
                    cm.Width = 150; 

                    MenuItem cm_i = new MenuItem();
                    cm_i.Header = "start state";
                    cm_i.Tag = sta.name;
                    cm_i.AddHandler(MenuItem.ClickEvent, new RoutedEventHandler(start_state_clicked));
                    cm_i.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                    cm_i.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                    cm_i.FontSize = 10;
                    cm_i.Foreground = Brushes.DarkSeaGreen;

                    BitmapImage cm_i_image = new BitmapImage();
                    cm_i_image.BeginInit();
                    Uri cm_i_Uri = new Uri("/PMisuseAn;component/images/startstate.gif", UriKind.RelativeOrAbsolute);
                    cm_i_image.UriSource = cm_i_Uri;
                    cm_i_image.EndInit();

                    Image cm_i_iconImage = new Image();
                    cm_i_iconImage.Source = cm_i_image;

                    cm_i.Icon = cm_i_iconImage;

                    MenuItem cm_i_e = new MenuItem();
                    cm_i_e.Header = "end state";
                    cm_i_e.Tag = sta.name;
                    cm_i_e.AddHandler(MenuItem.ClickEvent, new RoutedEventHandler(end_state_clicked));
                    cm_i_e.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                    cm_i_e.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                    cm_i_e.FontSize = 10;
                    cm_i_e.Foreground = Brushes.DarkRed;

                    BitmapImage cm_i_e_image = new BitmapImage();
                    cm_i_e_image.BeginInit();
                    Uri cm_i_e_Uri = new Uri("/PMisuseAn;component/images/stopstate.gif", UriKind.RelativeOrAbsolute);
                    cm_i_e_image.UriSource = cm_i_e_Uri;
                    cm_i_e_image.EndInit();

                    Image cm_i_e_iconImage = new Image();
                    cm_i_e_iconImage.Source = cm_i_e_image;

                    cm_i_e.Icon = cm_i_e_iconImage;

                    //MenuItem cm_mp = new MenuItem();
                    //cm_mp.Header = "mitigation point";
                    //cm_mp.Tag = sta.name;
                    //if (sta.isMitigationPoint == true)
                    //{
                    //    cm_mp.IsChecked = true;
                    //}
                    //cm_mp.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(mitigation_point_state_clicked));
                    //cm_mp.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(mitigation_point_state_clicked));
                    //cm_mp.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                    //cm_mp.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                    //cm_mp.FontSize = 10;
                    //cm_mp.Background = Brushes.LightYellow;
                    //cm_mp.IsCheckable = true;

                    MenuItem cm_mu = new MenuItem();
                    cm_mu.Header = "misuse point";
                    cm_mu.Tag = sta.name;
                    if (sta.isMisusePoint == true)
                    {
                        cm_mu.IsChecked = true;
                    }
                    cm_mu.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(misuse_point_state_clicked));
                    cm_mu.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(misuse_point_state_clicked));
                    cm_mu.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                    cm_mu.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                    cm_mu.FontSize = 10;
                   // cm_mu.Background = Brushes.OrangeRed;
                    cm_mu.IsCheckable = true;

                    MenuItem cm_m_mr = new MenuItem();
                    cm_m_mr.Header = "Mitigation references";
                    cm_m_mr.Tag = sta.name;

                    if (sta.isMisusePoint == false)
                    {
                        cm_m_mr.IsEnabled = false;
                    }
                    if (m_ref_s.isEmpty == false)
                    {
                        cm_m_mr.IsChecked = true;
                    }
                    cm_m_mr.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(mitigation_references_state_clicked));
                    cm_m_mr.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(mitigation_references_state_clicked));
                    cm_m_mr.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                    cm_m_mr.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                    cm_m_mr.FontSize = 10;
                    //cm_m_act.Background = Brushes.OrangeRed;
                    cm_m_mr.IsCheckable = true;

                    cm.Items.Add(cm_i);
                    cm.Items.Add(cm_i_e);
                    //cm.Items.Add(cm_mp);
                    cm.Items.Add(cm_mu);
                    cm.Items.Add(cm_m_mr);

                    item.ContextMenu = cm;

                    states.Items.Add(item);
                }
            }
        }

        private void loadStates(StateMachine machine)
        {
            states.Items.Clear();
            //string startState = MisUseAnObjectsDB.getStartState(machine.machineName, MainWindow.clusterName);
            string startState = "";
            if (machine.startState != null)
            {
                startState = machine.startState.name;
            }
            //string endState = MisUseAnObjectsDB.getEndState(machine.machineName, MainWindow.clusterName);
            string endState = "";
            if (machine.endState != null)
            {
                endState = machine.endState.name;
            }
            TreeViewItem item_n = new TreeViewItem();
            item_n.Header = "New..     ";
            item_n.Tag = "";
            item_n.FontStyle = FontStyles.Italic;
            item_n.Foreground = Brushes.Blue;
            item_n.AddHandler(TreeViewItem.SelectedEvent, new RoutedEventHandler(state_TreeViewItem_Selected));
            states.Items.Add(item_n);      

            foreach (State sta in machine.states)
            {
                if (!states.Items.Contains(sta.name))
                {
                    TreeViewItem item = new TreeViewItem();
                    item.Header = sta.name;
                    item.Tag = sta.name;
                    item.AddHandler(TreeViewItem.SelectedEvent, new RoutedEventHandler(state_TreeViewItem_Selected));
                    if (sta.name.Equals(startState))
                    {
                        item.Foreground = Brushes.DarkSeaGreen;
                    }
                    else if (sta.name.Equals(endState))
                    {
                        item.Foreground = Brushes.DarkRed;
                    }

                    //if (sta.isMitigationPoint == true)
                    //{
                    //    item.Background = Brushes.LightYellow;
                    //}
                    if (sta.isMisusePoint == true)
                    {
                        item.Background = Brushes.OrangeRed;
                    }

                    MitigationReferences m_ref_s = MisUseAnObjectsDB.loadStateMitigationReferencesDB(sta.name, machineName_, MainWindow.clusterName);

                    if (m_ref_s.isEmpty == false)
                    {
                        item.Background = Brushes.Green;
                    }

                    TreeViewItem item_action = new TreeViewItem();
                    item_action.Header = "New.. (action)";
                    item_action.FontStyle = FontStyles.Italic;
                    item_action.Foreground = Brushes.Blue;
                    item_action.Tag = "new," + sta.name;
                    item_action.AddHandler(TreeViewItem.SelectedEvent, new RoutedEventHandler(state_action_TreeViewItem_Selected));
                    item.Items.Add(item_action);
                    foreach (PMisuseAn.behaviour.model.Action action in sta.actions)
                    {
                        TreeViewItem item_act = new TreeViewItem();
                        item_act.Header = action.name;
                        item_act.Tag = action.name+"," + sta.name;
                        item_act.AddHandler(TreeViewItem.SelectedEvent, new RoutedEventHandler(state_action_TreeViewItem_Selected));
                        //if (action.isMitigationPoint == true)
                        //{
                        //    item_act.Background = Brushes.LightYellow;
                        //}
                        if (action.isMisusePoint == true)
                        {
                            item_act.Background = Brushes.OrangeRed;
                        }

                        MitigationReferences m_ref = MisUseAnObjectsDB.loadStateActionMitigationReferencesDB(action.name, sta.name, machineName_, MainWindow.clusterName);

                        if (m_ref.isEmpty == false)
                        {
                            item_act.Background = Brushes.Green;
                        }

                        ContextMenu cm_act = new System.Windows.Controls.ContextMenu();
                        cm_act.Height = 60;
                        cm_act.Width = 150;

                        //MenuItem cm_mp_act = new MenuItem();
                        //cm_mp_act.Header = "mitigation point";
                        //cm_mp_act.Tag = action.name + "," + sta.name;
                        //if (action.isMitigationPoint == true)
                        //{
                        //    cm_mp_act.IsChecked = true;
                        //}
                        //cm_mp_act.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(mitigation_point_state_action_clicked));
                        //cm_mp_act.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(mitigation_point_state_action_clicked));
                        //cm_mp_act.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                        //cm_mp_act.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                        //cm_mp_act.FontSize = 10;
                        //cm_mp_act.Background = Brushes.LightYellow;
                        //cm_mp_act.IsCheckable = true;

                        MenuItem cm_mu_act = new MenuItem();
                        cm_mu_act.Header = "misuse point";
                        cm_mu_act.Tag = action.name + "," + sta.name;
                        if (action.isMisusePoint == true)
                        {
                            cm_mu_act.IsChecked = true;
                        }
                        cm_mu_act.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(misuse_point_state_action_clicked));
                        cm_mu_act.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(misuse_point_state_action_clicked));
                        cm_mu_act.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                        cm_mu_act.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                        cm_mu_act.FontSize = 10;
                        //cm_mu_act.Background = Brushes.OrangeRed;
                        cm_mu_act.IsCheckable = true;

                        MenuItem cm_m_act = new MenuItem();
                        cm_m_act.Header = "Mitigation references";
                        cm_m_act.Tag = action.name + "," + sta.name;
                        
                        if (action.isMisusePoint == false)
                        {
                            cm_mu_act.IsEnabled = false;
                        }
                        if (m_ref.isEmpty == false)
                        {
                            cm_m_act.IsChecked = true;
                        }
                        cm_m_act.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(mitigation_references_state_action_clicked));
                        cm_m_act.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(mitigation_references_state_action_clicked));
                        cm_m_act.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                        cm_m_act.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                        cm_m_act.FontSize = 10;
                        //cm_m_act.Background = Brushes.OrangeRed;
                        cm_m_act.IsCheckable = true;

                        //cm_act.Items.Add(cm_mp_act);
                        cm_act.Items.Add(cm_mu_act);
                        cm_act.Items.Add(cm_m_act);

                        item_act.ContextMenu = cm_act;
                        item.Items.Add(item_act);
                    }

                    ContextMenu cm = new System.Windows.Controls.ContextMenu();
                    cm.Height = 110;
                    cm.Width = 150; 

                    MenuItem cm_i = new MenuItem();
                    cm_i.Header = "start state";
                    cm_i.Tag = sta.name;
                    cm_i.AddHandler(MenuItem.ClickEvent, new RoutedEventHandler(start_state_clicked));
                    cm_i.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                    cm_i.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                    cm_i.FontSize = 10;
                    cm_i.Foreground = Brushes.DarkSeaGreen;

                    BitmapImage cm_i_image = new BitmapImage();
                    cm_i_image.BeginInit();
                    Uri cm_i_Uri = new Uri("/PMisuseAn;component/images/startstate.gif", UriKind.RelativeOrAbsolute);
                    cm_i_image.UriSource = cm_i_Uri;
                    cm_i_image.EndInit();

                    Image cm_i_iconImage = new Image();
                    cm_i_iconImage.Source = cm_i_image;

                    cm_i.Icon = cm_i_iconImage;

                    MenuItem cm_i_e = new MenuItem();
                    cm_i_e.Header = "end state";
                    cm_i_e.Tag = sta.name;
                    cm_i_e.AddHandler(MenuItem.ClickEvent, new RoutedEventHandler(end_state_clicked));
                    cm_i_e.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                    cm_i_e.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                    cm_i_e.FontSize = 10;
                    cm_i_e.Foreground = Brushes.DarkRed;

                    BitmapImage cm_i_e_image = new BitmapImage();
                    cm_i_e_image.BeginInit();
                    Uri cm_i_e_Uri = new Uri("/PMisuseAn;component/images/stopstate.gif", UriKind.RelativeOrAbsolute);
                    cm_i_e_image.UriSource = cm_i_e_Uri;
                    cm_i_e_image.EndInit();

                    Image cm_i_e_iconImage = new Image();
                    cm_i_e_iconImage.Source = cm_i_e_image;

                    cm_i_e.Icon = cm_i_e_iconImage;

                    //MenuItem cm_mp = new MenuItem();
                    //cm_mp.Header = "mitigation point";
                    //cm_mp.Tag = sta.name;
                    //if (sta.isMitigationPoint == true)
                    //{
                    //    cm_mp.IsChecked = true;
                    //}
                    //cm_mp.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(mitigation_point_state_clicked));
                    //cm_mp.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(mitigation_point_state_clicked));
                    //cm_mp.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                    //cm_mp.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                    //cm_mp.FontSize = 10;
                    //cm_mp.Background = Brushes.LightYellow;
                    //cm_mp.IsCheckable = true;

                    MenuItem cm_mu = new MenuItem();
                    cm_mu.Header = "misuse point";
                    cm_mu.Tag = sta.name;
                    if (sta.isMisusePoint == true)
                    {
                        cm_mu.IsChecked = true;
                    }
                    cm_mu.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(misuse_point_state_clicked));
                    cm_mu.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(misuse_point_state_clicked));
                    cm_mu.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                    cm_mu.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                    cm_mu.FontSize = 10;
                    //cm_mu.Background = Brushes.OrangeRed;
                    cm_mu.IsCheckable = true;

                    MenuItem cm_m_mr = new MenuItem();
                    cm_m_mr.Header = "Mitigation references";
                    cm_m_mr.Tag = sta.name;

                    if (sta.isMisusePoint == false)
                    {
                        cm_m_mr.IsEnabled = false;
                    }
                    if (m_ref_s.isEmpty == false)
                    {
                        cm_m_mr.IsChecked = true;
                    }
                    cm_m_mr.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(mitigation_references_state_clicked));
                    cm_m_mr.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(mitigation_references_state_clicked));
                    cm_m_mr.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                    cm_m_mr.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                    cm_m_mr.FontSize = 10;
                    //cm_m_act.Background = Brushes.OrangeRed;
                    cm_m_mr.IsCheckable = true;
                                        
                    cm.Items.Add(cm_i);
                    cm.Items.Add(cm_i_e);
                    //cm.Items.Add(cm_mp);
                    cm.Items.Add(cm_mu);
                    cm.Items.Add(cm_m_mr);

                    item.ContextMenu = cm;

                    states.Items.Add(item);
                }
            }
        }

        private void start_state_clicked(object sender, RoutedEventArgs e)
        {
            MenuItem cm_i = (MenuItem)sender;
            string stateName = (string)cm_i.Tag;
            if (stateName != null)
            {
                machine_.startState = machine_.getStateX(stateName);
                //MisUseAnObjectsDB.addStateMachineStartStateDB(stateName,machineName_, MainWindow.clusterName);
                MisUseAnObjectsDB.addStateMachineDB(machine_, MainWindow.clusterName);

                loadStates();
                genStateMachineGraph();
            }
        }

        private void end_state_clicked(object sender, RoutedEventArgs e)
        {
            MenuItem cm_i = (MenuItem)sender;
            string stateName = (string)cm_i.Tag;
            if (stateName != null)
            {
                machine_.endState = machine_.getStateX(stateName);
                //MisUseAnObjectsDB.addStateMachineEndStateDB(stateName, machineName_, MainWindow.clusterName);
                MisUseAnObjectsDB.addStateMachineDB(machine_, MainWindow.clusterName);
                loadStates();
                genStateMachineGraph();
            }
        }

        private void mitigation_point_state_clicked(object sender, RoutedEventArgs e)
        {
            MenuItem cm_i = (MenuItem)sender;
            string stateName = (string)cm_i.Tag;           

            if (stateName != null)
            {
                if (cm_i.IsChecked == true)
                {
                    MisUseAnObjectsDB.addStateMitigationPointDB(stateName, machineName_, MainWindow.clusterName);
                }
                else if (cm_i.IsChecked == false)
                {
                    MisUseAnObjectsDB.removeStateMitigationPointDB(stateName, machineName_, MainWindow.clusterName);                
                }
                loadStates();
                genStateMachineGraph();
            }
        }

        private void mitigation_point_event_clicked(object sender, RoutedEventArgs e)
        {
            MenuItem cm_i = (MenuItem)sender;
            string eventName = (string)cm_i.Tag;

            if (eventName != null)
            {
                if (cm_i.IsChecked == true)
                {
                    MisUseAnObjectsDB.addEventMitigationPointDB(eventName, machineName_, MainWindow.clusterName);
                }
                else if (cm_i.IsChecked == false)
                {
                    MisUseAnObjectsDB.removeEventMitigationPointDB(eventName, machineName_, MainWindow.clusterName);
                }
                loadEvents();
                genStateMachineGraph();
            }
        }

        private void mitigation_point_transition_clicked(object sender, RoutedEventArgs e)
        {
            MenuItem cm_i = (MenuItem)sender;
            string tag_id = (string)cm_i.Tag;
            string[] tag_comps = tag_id.Split(',');
            string transitionName_t = tag_comps[0];
            string machineName_t = tag_comps[1];
            string startState_t = tag_comps[2];
            string endState_t = tag_comps[3];
            string associatedEvent_t = tag_comps[4];

            if (tag_id != null)
            {
                if (cm_i.IsChecked == true)
                {
                    MisUseAnObjectsDB.addTransitionMitigationPointDB(transitionName_t, startState_t,
                        endState_t, associatedEvent_t, machineName_t, MainWindow.clusterName);
                }
                else if (cm_i.IsChecked == false)
                {
                    MisUseAnObjectsDB.removeTransitionMitigationPointDB(transitionName_t, startState_t,
                        endState_t, associatedEvent_t, machineName_t, MainWindow.clusterName);
                }
                loadTransitions();
                genStateMachineGraph();
            }
        }

        private void mitigation_point_state_action_clicked(object sender, RoutedEventArgs e)
        {
            MenuItem cm_i = (MenuItem)sender;   
            string tag_id = (string)cm_i.Tag;
            string[] tag_split = tag_id.Split(',');

            string actionName = tag_split[0];
            string stateName = tag_split[1];

            if (stateName != null && actionName != null)
            {
                if (cm_i.IsChecked == true)
                {
                    MisUseAnObjectsDB.addStateActionMitigationPointDB(actionName, stateName, machineName_, MainWindow.clusterName);
                }
                else if (cm_i.IsChecked == false)
                {
                    MisUseAnObjectsDB.removeStateActionMitigationPointDB(actionName, stateName, machineName_, MainWindow.clusterName);                
                }
                loadStates();
                genStateMachineGraph();
            }
        }
        

        private void misuse_point_state_clicked(object sender, RoutedEventArgs e)
        {
            MenuItem cm_i = (MenuItem)sender;
            string stateName = (string)cm_i.Tag;           

            if (stateName != null)
            {
                if (cm_i.IsChecked == true)
                {
                    MisUseAnObjectsDB.addStateMisusePointDB(stateName, machineName_, MainWindow.clusterName);
                }
                else if (cm_i.IsChecked == false)
                {
                    MisUseAnObjectsDB.removeStateMisusePointDB(stateName, machineName_, MainWindow.clusterName);                
                }
                loadStates();
                genStateMachineGraph();
            }
        }

        private void misuse_point_event_clicked(object sender, RoutedEventArgs e)
        {
            MenuItem cm_i = (MenuItem)sender;
            string eventName = (string)cm_i.Tag;

            if (eventName != null)
            {
                if (cm_i.IsChecked == true)
                {
                    MisUseAnObjectsDB.addEventMisusePointDB(eventName, machineName_, MainWindow.clusterName);
                }
                else if (cm_i.IsChecked == false)
                {
                    MisUseAnObjectsDB.removeEventMisusePointDB(eventName, machineName_, MainWindow.clusterName);
                }
                loadEvents();
                genStateMachineGraph();
            }
        }

        private void misuse_point_transition_clicked(object sender, RoutedEventArgs e)
        {
            MenuItem cm_i = (MenuItem)sender;
            string tag_id = (string)cm_i.Tag;
            string[] tag_comps = tag_id.Split(',');
            string transitionName_t = tag_comps[0];
            string machineName_t = tag_comps[1];
            string startState_t = tag_comps[2];
            string endState_t = tag_comps[3];
            string associatedEvent_t = tag_comps[4];

            if (tag_id != null)
            {
                if (cm_i.IsChecked == true)
                {
                    MisUseAnObjectsDB.addTransitionMisusePointDB(transitionName_t, startState_t,
                        endState_t, associatedEvent_t, machineName_t, MainWindow.clusterName);
                }
                else if (cm_i.IsChecked == false)
                {
                    MisUseAnObjectsDB.removeTransitionMisusePointDB(transitionName_t, startState_t,
                        endState_t, associatedEvent_t, machineName_t, MainWindow.clusterName);
                }
                loadTransitions();
                genStateMachineGraph();
            }
        }

        private void misuse_point_state_action_clicked(object sender, RoutedEventArgs e)
        {
            MenuItem cm_i = (MenuItem)sender;
            string tag_id = (string)cm_i.Tag;
            string[] tag_split = tag_id.Split(',');

            string actionName = tag_split[0];
            string stateName = tag_split[1];

            if (stateName != null && actionName != null)
            {
                if (cm_i.IsChecked == true)
                {
                    //MisUseAnObjectsDB.addStateActionMisusePointDB(actionName, stateName, machineName_, MainWindow.clusterName);
                }
                else if (cm_i.IsChecked == false)
                {
                    //MisUseAnObjectsDB.removeStateActionMisusePointDB(actionName, stateName, machineName_, MainWindow.clusterName);
                }
                loadStates();
                genStateMachineGraph();
            }
        }

        private void mitigation_references_state_action_clicked(object sender, RoutedEventArgs e)
        {
            MenuItem cm_i = (MenuItem)sender;
            string tag_id = (string)cm_i.Tag;
            string[] tag_split = tag_id.Split(',');

            string actionName = tag_split[0];
            string stateName = tag_split[1];

            if (stateName != null && actionName != null)
            {
                MitigationReferences m_ref = MisUseAnObjectsDB.loadStateActionMitigationReferencesDB(actionName, stateName, machineName_, MainWindow.clusterName);
                
                string t_label = stateName+"("+actionName+")";
                MitigationReferenceWindow mrw = new MitigationReferenceWindow(this, m_ref, machineName_,t_label);
                mrw.Owner = (Window)this.Parent;
                mrw.ShowDialog();

                MisUseAnObjectsDB.addStateActionMitigationReferencesDB(actionName, stateName, m_ref, machineName_, MainWindow.clusterName);

                loadStates();
                loadTransitions();
                genStateMachineGraph();
            }
        }

        private void mitigation_references_state_clicked(object sender, RoutedEventArgs e)
        {
            MenuItem cm_i = (MenuItem)sender;
            string stateName = (string)cm_i.Tag;           
            
            if (stateName != null)
            {
                MitigationReferences m_ref = MisUseAnObjectsDB.loadStateMitigationReferencesDB(stateName, machineName_, MainWindow.clusterName);

                MitigationReferenceWindow mrw = new MitigationReferenceWindow(this, m_ref, machineName_, stateName);
                mrw.Owner = (Window)this.Parent;
                mrw.ShowDialog();

                MisUseAnObjectsDB.addStateMitigationReferencesDB(stateName, m_ref, machineName_, MainWindow.clusterName);

                loadStates();
                loadTransitions();
                genStateMachineGraph();
            }
        }

        private void mitigation_references_transition_clicked(object sender, RoutedEventArgs e)
        {
            MenuItem cm_i = (MenuItem)sender;
            string tag_id = (string)cm_i.Tag;
            string[] tag_comps = tag_id.Split(',');
            string transitionName_t = tag_comps[0];
            string machineName_t = tag_comps[1];
            string startState_t = tag_comps[2];
            string endState_t = tag_comps[3];
            string associatedEvent_t = tag_comps[4];

            if (tag_id != null)
            {
                MitigationReferences m_ref = MisUseAnObjectsDB.
                    loadTransitionMitigationReferencesDB(transitionName_t, machineName_t, MainWindow.clusterName);

                string t_label = transitionName_t + "(" + startState_t + ", " + endState_t + ", " + associatedEvent_t + ")";
                MitigationReferenceWindow mrw = new MitigationReferenceWindow(this, m_ref, machineName_, t_label);
                mrw.Owner = (Window)this.Parent;
                mrw.ShowDialog();

                MisUseAnObjectsDB.addTransitionMitigationReferencesDB(transitionName_t, m_ref, machineName_, MainWindow.clusterName);

                loadStates();
                loadTransitions();
                genStateMachineGraph();
            }
        }
        
        
        private void loadTransitions(StateMachine machine)
        {
            transitions.Items.Clear();
            TreeViewItem item_n = new TreeViewItem();
            item_n.Header = "New..   ";
            item_n.FontStyle = FontStyles.Italic;
            item_n.Foreground = Brushes.Blue;
            item_n.Tag = "new";
            item_n.AddHandler(TreeViewItem.SelectedEvent, new RoutedEventHandler(transition_TreeViewItem_Selected));
            transitions.Items.Add(item_n);

            foreach (Transition trans in machine.transitions)
            {
                string trans_tag = trans.transitionName + "," + trans.machineName + "," + trans.startState +
                    "," + trans.endState + "," + trans.associatedEevent;
                string trans_content = trans.transitionName + "(" + trans.startState +
                    "," + trans.endState + "," + trans.associatedEevent+")";
                if (!transitions.Items.Contains(trans_content))
                {
                    TreeViewItem item = new TreeViewItem();
                    item.Header = trans_content;
                    item.Tag = trans_tag;
                    item.AddHandler(TreeViewItem.SelectedEvent, new RoutedEventHandler(transition_TreeViewItem_Selected));

                    //if (trans.isMitigationPoint == true)
                    //{
                    //    item.Background = Brushes.LightYellow;
                    //}
                    if (trans.isMisusePoint == true)
                    {
                        item.Background = Brushes.OrangeRed;
                    }

                    MitigationReferences m_ref_s = MisUseAnObjectsDB.loadTransitionMitigationReferencesDB(trans.transitionName, machineName_, MainWindow.clusterName);

                    if (m_ref_s.isEmpty == false)
                    {
                        item.Background = Brushes.Green;
                    }

                    ContextMenu cm_trans = new System.Windows.Controls.ContextMenu();
                    cm_trans.Height = 60;
                    cm_trans.Width = 150;

                    //MenuItem cm_mp_trans = new MenuItem();
                    //cm_mp_trans.Header = "mitigation point";
                    //cm_mp_trans.Tag = trans_tag;
                    //if (trans.isMitigationPoint == true)
                    //{
                    //    cm_mp_trans.IsChecked = true;
                    //}
                    //cm_mp_trans.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(mitigation_point_transition_clicked));
                    //cm_mp_trans.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(mitigation_point_transition_clicked));
                    //cm_mp_trans.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                    //cm_mp_trans.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                    //cm_mp_trans.FontSize = 10;
                    //cm_mp_trans.Background = Brushes.LightYellow;
                    //cm_mp_trans.IsCheckable = true;

                    MenuItem cm_mu_trans = new MenuItem();
                    cm_mu_trans.Header = "misuse point";
                    cm_mu_trans.Tag = trans_tag;
                    if (trans.isMisusePoint == true)
                    {
                        cm_mu_trans.IsChecked = true;
                    }
                    cm_mu_trans.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(misuse_point_transition_clicked));
                    cm_mu_trans.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(misuse_point_transition_clicked));
                    cm_mu_trans.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                    cm_mu_trans.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                    cm_mu_trans.FontSize = 10;
                    //cm_mu_trans.Background = Brushes.OrangeRed;
                    cm_mu_trans.IsCheckable = true;

                    MenuItem cm_m_mr = new MenuItem();
                    cm_m_mr.Header = "Mitigation references";
                    cm_m_mr.Tag = trans_tag;
                    if (trans.isMisusePoint == false)
                    {
                        cm_m_mr.IsEnabled = false;
                    }
                    if (m_ref_s.isEmpty == false)
                    {
                        cm_m_mr.IsChecked = true;
                    }
                    cm_m_mr.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(mitigation_references_transition_clicked));
                    cm_m_mr.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(mitigation_references_transition_clicked));
                    cm_m_mr.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                    cm_m_mr.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                    cm_m_mr.FontSize = 10;
                    //cm_m_act.Background = Brushes.OrangeRed;
                    cm_m_mr.IsCheckable = true;

                    //cm_trans.Items.Add(cm_mp_trans);
                    cm_trans.Items.Add(cm_mu_trans);
                    cm_trans.Items.Add(cm_m_mr);

                    item.ContextMenu = cm_trans;
                    
                    transitions.Items.Add(item);
                }
            }
        }
        
        private void loadTransitions()
        {
            transitions.Items.Clear();
            TreeViewItem item_n = new TreeViewItem();
            item_n.Header = "New..   ";
            item_n.FontStyle = FontStyles.Italic;
            item_n.Foreground = Brushes.Blue;
            item_n.Tag = "new";
            item_n.AddHandler(TreeViewItem.SelectedEvent, new RoutedEventHandler(transition_TreeViewItem_Selected));
            transitions.Items.Add(item_n);

            //allExistingStateTransitions = MisUseAnObjectsDB.loadAllStateTransitions(machineName_, MainWindow.clusterName);
            allExistingStateTransitions = machine_.transitions;
            if(allExistingStateTransitions  != null)
            foreach (Transition trans in allExistingStateTransitions)
            {
                string trans_tag = trans.transitionName + "," + trans.machineName + "," + trans.startState +
                    "," + trans.endState + "," + trans.associatedEevent;
                string trans_content = trans.transitionName + "(" + trans.startState +
                    "," + trans.endState + "," + trans.associatedEevent + ")";
                if (!transitions.Items.Contains(trans_content))
                {
                    TreeViewItem item = new TreeViewItem();
                    item.Header = trans_content;
                    item.Tag = trans_tag;
                    item.AddHandler(TreeViewItem.SelectedEvent, new RoutedEventHandler(transition_TreeViewItem_Selected));
                    
                    //if (trans.isMitigationPoint == true)
                    //{
                    //    item.Background = Brushes.LightYellow;
                    //}
                    if (trans.isMisusePoint == true)
                    {
                        item.Background = Brushes.OrangeRed;
                    }

                    MitigationReferences m_ref_s = MisUseAnObjectsDB.loadTransitionMitigationReferencesDB(trans.transitionName, machineName_, MainWindow.clusterName);

                    if (m_ref_s.isEmpty == false)
                    {
                        item.Background = Brushes.Green;
                    }
                    
                    ContextMenu cm_trans = new System.Windows.Controls.ContextMenu();
                    cm_trans.Height = 60;
                    cm_trans.Width = 150;

                    //MenuItem cm_mp_trans = new MenuItem();
                    //cm_mp_trans.Header = "mitigation point";
                    //cm_mp_trans.Tag = trans_tag;
                    //if (trans.isMitigationPoint == true)
                    //{
                    //    cm_mp_trans.IsChecked = true;
                    //}
                    //cm_mp_trans.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(mitigation_point_transition_clicked));
                    //cm_mp_trans.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(mitigation_point_transition_clicked));
                    //cm_mp_trans.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                    //cm_mp_trans.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                    //cm_mp_trans.FontSize = 10;
                    //cm_mp_trans.Background = Brushes.LightYellow;
                    //cm_mp_trans.IsCheckable = true;

                    MenuItem cm_mu_trans = new MenuItem();
                    cm_mu_trans.Header = "misuse point";
                    cm_mu_trans.Tag = trans_tag;
                    if (trans.isMisusePoint == true)
                    {
                        cm_mu_trans.IsChecked = true;
                    }
                    cm_mu_trans.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(misuse_point_transition_clicked));
                    cm_mu_trans.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(misuse_point_transition_clicked));
                    cm_mu_trans.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                    cm_mu_trans.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                    cm_mu_trans.FontSize = 10;
                    //cm_mu_trans.Background = Brushes.OrangeRed;
                    cm_mu_trans.IsCheckable = true;

                    MenuItem cm_m_mr = new MenuItem();
                    cm_m_mr.Header = "Mitigation references";
                    cm_m_mr.Tag = trans_tag;
                    if (trans.isMisusePoint == false)
                    {
                        cm_m_mr.IsEnabled = false;
                    }
                    if (m_ref_s.isEmpty == false)
                    {
                        cm_m_mr.IsChecked = true;
                    }
                    cm_m_mr.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(mitigation_references_transition_clicked));
                    cm_m_mr.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(mitigation_references_transition_clicked));
                    cm_m_mr.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                    cm_m_mr.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                    cm_m_mr.FontSize = 10;
                    //cm_m_act.Background = Brushes.OrangeRed;
                    cm_m_mr.IsCheckable = true;

                    //cm_trans.Items.Add(cm_mp_trans);
                    cm_trans.Items.Add(cm_mu_trans);
                    cm_trans.Items.Add(cm_m_mr);

                    item.ContextMenu = cm_trans;
                    
                    transitions.Items.Add(item);
                }
            }
        }  

        private void loadEvents(StateMachine machine)
        {
            events.Items.Clear();

            TreeViewItem item_n = new TreeViewItem();
            item_n.Header = "New..     ";
            item_n.Tag = "";
            item_n.FontStyle = FontStyles.Italic;
            item_n.Foreground = Brushes.Blue;
            item_n.AddHandler(TreeViewItem.SelectedEvent, new RoutedEventHandler(event_TreeViewItem_Selected));
            events.Items.Add(item_n); 

            foreach (Event eve in machine.events)
            {
                if (!events.Items.Contains(eve.name))
                {
                    TreeViewItem item = new TreeViewItem();
                    item.Header = eve.name;
                    item.Tag = eve.name;
                    item.AddHandler(TreeViewItem.SelectedEvent, new RoutedEventHandler(event_TreeViewItem_Selected));
                    //if (eve.isMitigationPoint == true)
                    //{
                    //    item.Background = Brushes.LightYellow;
                    //}
                    //if (eve.isMisusePoint == true)
                    //{
                    //    item.Background = Brushes.OrangeRed;
                    //}

                    //ContextMenu cm_event = new System.Windows.Controls.ContextMenu();
                    //cm_event.Height = 62;
                    //cm_event.Width = 130;

                    //MenuItem cm_mp_event = new MenuItem();
                    //cm_mp_event.Header = "mitigation point";
                    //cm_mp_event.Tag = eve.name;
                    //if (eve.isMitigationPoint == true)
                    //{
                    //    cm_mp_event.IsChecked = true;
                    //}
                    //cm_mp_event.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(mitigation_point_event_clicked));
                    //cm_mp_event.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(mitigation_point_event_clicked));
                    //cm_mp_event.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                    //cm_mp_event.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                    //cm_mp_event.FontSize = 10;
                    //cm_mp_event.Background = Brushes.LightYellow;
                    //cm_mp_event.IsCheckable = true;

                    //MenuItem cm_mu_event = new MenuItem();
                    //cm_mu_event.Header = "misuse point";
                    //cm_mu_event.Tag = eve.name;
                    //if (eve.isMisusePoint == true)
                    //{
                    //    cm_mu_event.IsChecked = true;
                    //}
                    //cm_mu_event.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(misuse_point_event_clicked));
                    //cm_mu_event.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(misuse_point_event_clicked));
                    //cm_mu_event.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                    //cm_mu_event.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                    //cm_mu_event.FontSize = 10;
                    //cm_mu_event.Background = Brushes.OrangeRed;
                    //cm_mu_event.IsCheckable = true;

                    //cm_event.Items.Add(cm_mp_event);
                    //cm_event.Items.Add(cm_mu_event);

                    //item.ContextMenu = cm_event;
                    
                    events.Items.Add(item);
                }
            }
        }

        private void reloadEntsInComboBox()
        {
            //allExisitngEvents = MisUseAnObjectsDB.loadAllEvents(machineName_, MainWindow.clusterName);
            allExisitngEvents = machine_.events;

            start_state_cb.Items.Clear();
            end_state_cb.Items.Clear();
            associated_event_cb.Items.Clear();
            
            //allExistingStates = MisUseAnObjectsDB.loadAllStates(machineName_, MainWindow.clusterName);
            allExistingStates = machine_.states;
            if(allExistingStates != null)
            foreach (State state in allExistingStates)
            {
                start_state_cb.Items.Add(state.name);
                end_state_cb.Items.Add(state.name);
            }

            if (allExisitngEvents != null)
            foreach (Event event_ in allExisitngEvents)
            {
                associated_event_cb.Items.Add(event_.name);
            }
        }

        bool existingEvent(string eventName)
        {
            bool exist = false;

            foreach (Event eventx in machine_.events)
            {
                if (eventx.name.Equals(eventName))
                {
                    exist = true;
                    break;
                }
            }
            
            //if(allExisitngEvents == null)
            //{
            //    allExisitngEvents = MisUseAnObjectsDB.loadAllEvents(machineName_, MainWindow.clusterName);
            //}
            //if (allExisitngEvents != null)
            //foreach (Event eve in allExisitngEvents)
            //{
            //    if (eve.name.Equals(eventName))
            //    {
            //        exist = true;
            //        break;
            //    }
            //}
            return exist;
        }

        bool existingState(string stateName)
        {
            bool exist = false;

            foreach (State statex in machine_.states)
            {
                if (statex.name.Equals(stateName))
                {
                    exist = true;
                    break;
                }
            }


            //if (allExistingStates == null)
            //{
            //    allExistingStates = MisUseAnObjectsDB.loadAllStates(machineName_, MainWindow.clusterName);
            //}

            //if (allExistingStates != null)
            //foreach (State eve in allExistingStates)
            //{
            //    if (eve.name.Equals(stateName))
            //    {
            //        exist = true;
            //        break;
            //    }
            //}
            return exist;
        }


        bool existingStateAction(string stateName, string actionName)
        {
            bool exist = false;

            foreach (State statex in machine_.states)
            {
                if (statex.name.Equals(stateName))
                {
                    foreach (PMisuseAn.behaviour.model.Action actx in statex.actions)
                    {
                        if (actx.name.Equals(actionName))
                        {
                            exist = true;
                            break;
                        }
                    }
                }
            }

            //if (allExistingStateActions == null)
            //{
            //    allExistingStateActions = MisUseAnObjectsDB.loadAllStateActions(machineName_, stateName, MainWindow.clusterName);

            //}
            //if(allExistingStateActions != null)
            //foreach (PMisuseAn.behaviour.model.Action action in allExistingStateActions)
            //{
            //    if (action.name.Equals(actionName))
            //    {
            //        exist = true;
            //        break;
            //    }
            //}
            return exist;
        }

        private void new_event_trigger_CheckedUnchecked(object sender, RoutedEventArgs e)
        {
            if (loadingTriggers == false)
            {
                CheckBox d_cb = (CheckBox)sender;
                string eventName = new_ent_name_tb.Text;
                eventName = eventName.Trim();
                eventName = eventName.TrimEnd('\n');
                eventName = eventName.TrimEnd('\r');

                if (eventName.Count() == 0)
                {
                    MessageBoxResult result = MessageBox.Show(this, "NULL event name...",
                                "error", MessageBoxButton.OK,
                                MessageBoxImage.Information);

                    d_cb.IsChecked = false;

                    return;
                }
                if (isEventUpdate == false)
                {
                    if (existingEvent(eventName) == true)
                    {
                        MessageBoxResult result = MessageBox.Show(this, eventName + " event already exist...",
                                    "Conflict", MessageBoxButton.OK,
                                    MessageBoxImage.Information);

                        d_cb.IsChecked = false;

                        return;
                    }
                }

                if (newEvent == null)
                {
                    newEvent = new Event();
                    newEvent.machineName = machineName_;
                    newEvent.clusterName = MainWindow.clusterName;
                }
                newEvent.name = eventName;

                string eventType = "";
                if (request_event_rb.IsChecked == true)
                {
                    eventType = "request";
                }
                else
                {
                    eventType = "response";
                }
                newEvent.type = eventType;

                string trigger = (string)d_cb.Tag;

                if (newEvent.triggers.Contains(trigger))
                {
                    newEvent.removeTrigger(trigger);
                    //MisUseAnObjectsDB.deleteEventTriggerDB(newEvent.name, trigger, machineName_, MainWindow.clusterName);
                }
                else
                {
                    newEvent.addTrigger(trigger);
                    //MisUseAnObjectsDB.addEventDB(newEvent, MainWindow.clusterName);
                }
            }            
        }

        private void state_action_op_att_Checked(object sender, RoutedEventArgs e)
        {
            CheckBox d_cb = (CheckBox)sender;
            string tag_id = (string)d_cb.Tag;

            string actionName = new_ent_name_tb.Text;
            actionName = actionName.Trim();
            actionName = actionName.TrimEnd('\n');
            actionName = actionName.TrimEnd('\r');

            if (actionName.Count() == 0)
            {
                MessageBoxResult result = MessageBox.Show(this, "NULL action name...",
                            "error", MessageBoxButton.OK,
                            MessageBoxImage.Information);

                d_cb.IsChecked = false;

                return;
            }
            if (isStateActionUpdate == false)
            {
                if (existingStateAction(actionName, stateName_) == true)
                {
                    MessageBoxResult result = MessageBox.Show(this, actionName + " action already exist...",
                                "Conflict", MessageBoxButton.OK,
                                MessageBoxImage.Information);

                    d_cb.IsChecked = false;

                    return;
                }
            }

            if (newAction == null)
            {
                newAction = new PMisuseAn.behaviour.model.Action();
                newAction.machineName = machineName_;
                newAction.stateName = stateName_;
                newAction.clusterName = MainWindow.clusterName;
            }
            newAction.name = actionName;

            if (newAction.operationalAttributes_.Contains(tag_id))
            {
                newAction.removeOperationalAttribute(tag_id);
                //MisUseAnObjectsDB.deleteStateActionOperationalAttributeDB(machineName_, stateName_, actionName, tag_id, MainWindow.clusterName);
            }
            else
            {
                newAction.addOperationalAttribute(tag_id);
                //MisUseAnObjectsDB.addStateActionOperationalAttributeDB(newAction, tag_id, MainWindow.clusterName);
            }
        }

        private void event_op_att_Checked(object sender, RoutedEventArgs e)
        {
            CheckBox d_cb = (CheckBox)sender;
            string tag_id = (string)d_cb.Tag;

            string eventName = new_ent_name_tb.Text;
            eventName = eventName.Trim();
            eventName = eventName.TrimEnd('\n');
            eventName = eventName.TrimEnd('\r');

            if (eventName.Count() == 0)
            {
                MessageBoxResult result = MessageBox.Show(this, "NULL event name...",
                            "error", MessageBoxButton.OK,
                            MessageBoxImage.Information);

                d_cb.IsChecked = false;

                return;
            }
            if (isEventUpdate == false)
            {
                if (existingEvent(eventName) == true)
                {
                    MessageBoxResult result = MessageBox.Show(this, eventName + " event already exist...",
                                "Conflict", MessageBoxButton.OK,
                                MessageBoxImage.Information);

                    d_cb.IsChecked = false;

                    return;
                }
            }

            if (newEvent == null)
            {
                newEvent = new Event();
                newEvent.machineName = machineName_;                
                newEvent.clusterName = MainWindow.clusterName;
            }
            string eventDesc = new_ent_desc_tb.Text;
            newEvent.name = eventName;
            newEvent.description = eventDesc;

            string eventType = "";
            if (request_event_rb.IsChecked == true)
            {
                eventType = "request";
            }
            else
            {
                eventType = "response";
            }
            newEvent.type = eventType;

            if (newEvent.operationalAttributes_.Contains(tag_id))
            {
                newEvent.removeOperationalAttribute(tag_id);
                //MisUseAnObjectsDB.deleteEventOperationalAttributeDB(tag_id, eventName, machineName_, MainWindow.clusterName);
            }
            else
            {
                newEvent.addOperationalAttribute(tag_id);
                //MisUseAnObjectsDB.addEventOperationalAttributeDB(newEvent, tag_id, MainWindow.clusterName);
            }
        }

        private void apply_new_event_b_Click(object sender, RoutedEventArgs e)
        {
            string eventName = new_ent_name_tb.Text;
            eventName = eventName.Trim();
            eventName = eventName.TrimEnd('\n');
            eventName = eventName.TrimEnd('\r');
           
            if (eventName.Count() == 0)
            {
                MessageBoxResult result = MessageBox.Show(this, "NULL event name...",
                            "error", MessageBoxButton.OK,
                            MessageBoxImage.Information);
                return;
            }

            if (isEventUpdate == false)
            {
                if (existingEvent(eventName) == true)
                {
                    MessageBoxResult result = MessageBox.Show(this, eventName + " event already exist...",
                                "Conflict", MessageBoxButton.OK,
                                MessageBoxImage.Information);

                    return;
                }
            }

            if (newEvent == null)
            {
                newEvent = new Event();
                newEvent.machineName = machineName_;
                newEvent.clusterName = MainWindow.clusterName;
            }

            string eventDesc = new_ent_desc_tb.Text;
            newEvent.name = eventName;            
            newEvent.description = eventDesc;

            string eventType = "";
            if (request_event_rb.IsChecked == true)
            {
                eventType = "request";
            }
            else
            {
                eventType = "response";
            }
            newEvent.type = eventType;

            //MisUseAnObjectsDB.addEventDB(newEvent, MainWindow.clusterName);
            machine_.addEvent(newEvent);
            MisUseAnObjectsDB.addStateMachineDB(machine_, MainWindow.clusterName);


            TreeViewItem tvi = new TreeViewItem();
            tvi.Tag = newEvent.name;
            tvi.Header = newEvent.name;
            tvi.AddHandler(TreeViewItem.SelectedEvent, new RoutedEventHandler(event_TreeViewItem_Selected));                     
                        
            events.Items.Add(tvi);

            //allExisitngEvents = MisUseAnObjectsDB.loadAllEvents(machineName_, MainWindow.clusterName);
            allExisitngEvents = machine_.events;
            //allExisitngEvents.Add(newEvent);

            newEvent = new Event();
            newEvent.machineName = machineName_;
            newEvent.clusterName = MainWindow.clusterName;
            //loadAttributesToNewEventCategoryList();
            new_ent_name_tb.Text = "";
            new_ent_desc_tb.Text = "";

            loadingTriggers = true;
            time_event_cb.IsChecked = false;
            call_event_cb.IsChecked = false;
            signal_event_cb.IsChecked = false;
            change_event_cb.IsChecked = false;
            loadingTriggers = false;

            new_ent_name_tb.Visibility = System.Windows.Visibility.Hidden;
            new_ent_Name_l.Visibility = System.Windows.Visibility.Hidden;
            apply_new_event_b.Visibility = System.Windows.Visibility.Hidden;
            new_ent_desc_tb.Visibility = System.Windows.Visibility.Hidden;
            new_event_ppties_gb.Visibility = System.Windows.Visibility.Hidden;
            desc_l.Visibility = System.Windows.Visibility.Hidden;
            update_event_b.Visibility = System.Windows.Visibility.Hidden;
            delete_event_b.Visibility = System.Windows.Visibility.Hidden;
            define_state_b.Visibility = System.Windows.Visibility.Hidden;
            update_state_b.Visibility = System.Windows.Visibility.Hidden;
            delete_state_b.Visibility = System.Windows.Visibility.Hidden;
            operational_atts_gb.Visibility = System.Windows.Visibility.Hidden;
            state_action_apply_b.Visibility = System.Windows.Visibility.Hidden;
            state_action_update_b.Visibility = System.Windows.Visibility.Hidden;
            state_action_delete_b.Visibility = System.Windows.Visibility.Hidden;
            transitionPolicies_gb.Visibility = System.Windows.Visibility.Hidden;
            update_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            apply_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            start_state_l.Visibility = System.Windows.Visibility.Hidden;
            start_state_cb.Visibility = System.Windows.Visibility.Hidden;
            ass_event_l.Visibility = System.Windows.Visibility.Hidden;
            associated_event_cb.Visibility = System.Windows.Visibility.Hidden;
            end_state_l.Visibility = System.Windows.Visibility.Hidden;
            end_state_cb.Visibility = System.Windows.Visibility.Hidden;
            delete_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            isCallableTransition_cb.Visibility = System.Windows.Visibility.Hidden;
            
            //genStateMachineGraph();
        }

        private void update_event_b_Click(object sender, RoutedEventArgs e)
        {
            string eventName = new_ent_name_tb.Text;
            eventName = eventName.Trim();
            eventName = eventName.TrimEnd('\n');
            eventName = eventName.TrimEnd('\r');

            if (eventName.Count() == 0)
            {
                MessageBoxResult result = MessageBox.Show(this, "NULL event name...",
                            "error", MessageBoxButton.OK,
                            MessageBoxImage.Information);
                return;
            }

            if (isEventUpdate == false)
            {
                if (existingEvent(eventName) == true)
                {
                    MessageBoxResult result = MessageBox.Show(this, eventName + " event already exist...",
                                "Conflict", MessageBoxButton.OK,
                                MessageBoxImage.Information);

                    return;
                }
  
            }

            if (newEvent == null)
            {
                newEvent = new Event();
                newEvent.clusterName = MainWindow.clusterName;
                return;
            }

            string eventDesc = new_ent_desc_tb.Text;
            newEvent.name = eventName;
            newEvent.description = eventDesc;

            string eventType = "";
            if (request_event_rb.IsChecked == true)
            {
                eventType = "request";
            }
            else
            {
                eventType = "response";
            }
            newEvent.type = eventType;

            //MisUseAnObjectsDB.updateEventDB(newEvent, MainWindow.clusterName);
            machine_.updateEvent(newEvent);
            MisUseAnObjectsDB.addStateMachineDB(machine_, MainWindow.clusterName);

            allExisitngEvents = MisUseAnObjectsDB.loadAllEvents(machineName_, MainWindow.clusterName);
                        
            newEvent = new Event();
            newEvent.machineName = machineName_;
            newEvent.clusterName = MainWindow.clusterName;
            //reloadAttInNew_eventList();
            //loadAttributesToNewEventCategoryList();
            new_ent_name_tb.Text = "";
            new_ent_desc_tb.Text = "";

            loadingTriggers = true;
            time_event_cb.IsChecked = false;
            call_event_cb.IsChecked = false;
            signal_event_cb.IsChecked = false;
            change_event_cb.IsChecked = false;
            loadingTriggers = false;

            new_ent_name_tb.Visibility = System.Windows.Visibility.Hidden;
            new_ent_Name_l.Visibility = System.Windows.Visibility.Hidden;
            apply_new_event_b.Visibility = System.Windows.Visibility.Hidden;
            new_ent_desc_tb.Visibility = System.Windows.Visibility.Hidden;
            new_event_ppties_gb.Visibility = System.Windows.Visibility.Hidden;
            desc_l.Visibility = System.Windows.Visibility.Hidden;
            update_event_b.Visibility = System.Windows.Visibility.Hidden;
            delete_event_b.Visibility = System.Windows.Visibility.Hidden;
            define_state_b.Visibility = System.Windows.Visibility.Hidden;
            delete_state_b.Visibility = System.Windows.Visibility.Hidden;
            update_state_b.Visibility = System.Windows.Visibility.Hidden;
            operational_atts_gb.Visibility = System.Windows.Visibility.Hidden;
            state_action_apply_b.Visibility = System.Windows.Visibility.Hidden;
            state_action_update_b.Visibility = System.Windows.Visibility.Hidden;
            state_action_delete_b.Visibility = System.Windows.Visibility.Hidden;
            transitionPolicies_gb.Visibility = System.Windows.Visibility.Hidden;
            update_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            apply_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            start_state_l.Visibility = System.Windows.Visibility.Hidden;
            start_state_cb.Visibility = System.Windows.Visibility.Hidden;
            ass_event_l.Visibility = System.Windows.Visibility.Hidden;
            associated_event_cb.Visibility = System.Windows.Visibility.Hidden;
            end_state_l.Visibility = System.Windows.Visibility.Hidden;
            end_state_cb.Visibility = System.Windows.Visibility.Hidden;
            delete_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            isCallableState_cb.Visibility = System.Windows.Visibility.Hidden;
            isCallableTransition_cb.Visibility = System.Windows.Visibility.Hidden;

            genStateMachineGraph();
        }

        private void delete_event_b_Click(object sender, RoutedEventArgs e)
        {
            string eventName = new_ent_name_tb.Text;
            eventName = eventName.Trim();
            eventName = eventName.TrimEnd('\n');
            eventName = eventName.TrimEnd('\r');

            if (eventName.Count() >0)
            {
                MessageBoxResult result = MessageBox.Show(this, "confirm delete of "+ eventName+" event",
                            "Confirm", MessageBoxButton.YesNo,
                            MessageBoxImage.Information);

                if (result == MessageBoxResult.No)
                {
                    return;
                }
                else
                {
                    //MisUseAnObjectsDB.deleteEventDB(machineName_, eventName, MainWindow.clusterName);
                    if (machine_ != null)
                    {
                        machine_.removeEvent(eventName);
                        MisUseAnObjectsDB.addStateMachineDB(machine_, MainWindow.clusterName);
                    }
                    //allExisitngEvents = MisUseAnObjectsDB.loadAllEvents(machineName_, MainWindow.clusterName);
                    allExisitngEvents = machine_.events;
                    newEvent = new Event();
                    newEvent.machineName = machineName_;
                    newEvent.clusterName = MainWindow.clusterName;
                    //reloadAttInNew_eventList();
                    //loadAttributesToNewEventCategoryList();
                    new_ent_name_tb.Text = "";
                    new_ent_desc_tb.Text = "";

                    loadingTriggers = true;
                    time_event_cb.IsChecked = false;
                    call_event_cb.IsChecked = false;
                    signal_event_cb.IsChecked = false;
                    change_event_cb.IsChecked = false;
                    loadingTriggers = false;

                    new_ent_name_tb.Visibility = System.Windows.Visibility.Hidden;
                    new_ent_Name_l.Visibility = System.Windows.Visibility.Hidden;
                    apply_new_event_b.Visibility = System.Windows.Visibility.Hidden;
                    new_ent_desc_tb.Visibility = System.Windows.Visibility.Hidden;
                    new_event_ppties_gb.Visibility = System.Windows.Visibility.Hidden;
                    desc_l.Visibility = System.Windows.Visibility.Hidden;
                    update_event_b.Visibility = System.Windows.Visibility.Hidden;
                    delete_event_b.Visibility = System.Windows.Visibility.Hidden;
                    delete_state_b.Visibility = System.Windows.Visibility.Hidden;
                    update_state_b.Visibility = System.Windows.Visibility.Hidden;
                    define_state_b.Visibility = System.Windows.Visibility.Hidden;
                    operational_atts_gb.Visibility = System.Windows.Visibility.Hidden;
                    state_action_apply_b.Visibility = System.Windows.Visibility.Hidden;
                    state_action_update_b.Visibility = System.Windows.Visibility.Hidden;
                    state_action_delete_b.Visibility = System.Windows.Visibility.Hidden;
                    transitionPolicies_gb.Visibility = System.Windows.Visibility.Hidden;
                    update_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
                    apply_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
                    start_state_l.Visibility = System.Windows.Visibility.Hidden;
                    start_state_cb.Visibility = System.Windows.Visibility.Hidden;
                    ass_event_l.Visibility = System.Windows.Visibility.Hidden;
                    associated_event_cb.Visibility = System.Windows.Visibility.Hidden;
                    end_state_l.Visibility = System.Windows.Visibility.Hidden;
                    end_state_cb.Visibility = System.Windows.Visibility.Hidden;
                    delete_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
                    isCallableState_cb.Visibility = System.Windows.Visibility.Hidden;
                    isCallableTransition_cb.Visibility = System.Windows.Visibility.Hidden;

                    foreach (TreeViewItem item in events.Items)
                    {
                        if (item.Tag.Equals(eventName))
                        {
                            events.Items.Remove(item);
                            break;
                        }
                    }
                    loadTransitions();                   
                }
            }
            genStateMachineGraph();
        }

        private void define_state_b_Click(object sender, RoutedEventArgs e)
        {
            string stateName = new_ent_name_tb.Text;
            stateName = stateName.Trim();
            stateName = stateName.TrimEnd('\n');
            stateName = stateName.TrimEnd('\r');

            if (stateName.Count() == 0)
            {
                MessageBoxResult result = MessageBox.Show(this, "NULL state name...",
                            "error", MessageBoxButton.OK,
                            MessageBoxImage.Information);
                return;
            }

            if (isStateUpdate == false)
            {
                if (existingState(stateName) == true)
                {
                    MessageBoxResult result = MessageBox.Show(this, stateName + " state already exist...",
                                "Conflict", MessageBoxButton.OK,
                                MessageBoxImage.Information);

                    return;
                }
            }


            if (newState == null)
            {
                newState = new State();
                newState.clusterName = MainWindow.clusterName;
            }

            newState.name = stateName;
            newState.machineName = machineName_;
            string stateDesc = new_ent_desc_tb.Text;
            newState.description = stateDesc;

            if (isCallableState_cb.IsChecked == true)
            {
                newState.isCallable = true;
            }
            else
            {
                newState.isCallable = false;
            }

            //MisUseAnObjectsDB.addStateDB(newState, MainWindow.clusterName);
            machine_.addState(newState);
            MisUseAnObjectsDB.addStateMachineDB(machine_, MainWindow.clusterName);
            

            TreeViewItem tvi = new TreeViewItem();
            tvi.Tag = newState.name;
            tvi.Header = newState.name;
            tvi.AddHandler(TreeViewItem.SelectedEvent, new RoutedEventHandler(state_TreeViewItem_Selected));
            
            if (newState.name.Equals(startState))
            {
                tvi.Foreground = Brushes.DarkSeaGreen;
            }
            else if (newState.name.Equals(endState))
            {
                tvi.Foreground = Brushes.DarkRed;
            }

            //if (newState.isMitigationPoint == true)
            //{
            //    tvi.Background = Brushes.LightYellow;
            //}
            if (newState.isMisusePoint == true)
            {
                tvi.Background = Brushes.OrangeRed;
            }

            MitigationReferences m_ref_s = MisUseAnObjectsDB.loadStateMitigationReferencesDB(newState.name, machineName_, MainWindow.clusterName);

            if (m_ref_s.isEmpty == false)
            {
                tvi.Background = Brushes.Green;
            }

            TreeViewItem item_action = new TreeViewItem();
            item_action.Header = "New.. (action)";
            item_action.FontStyle = FontStyles.Italic;
            item_action.Foreground = Brushes.Blue;
            item_action.Tag = "new," + newState.name;
            item_action.AddHandler(TreeViewItem.SelectedEvent, new RoutedEventHandler(state_action_TreeViewItem_Selected));
            tvi.Items.Add(item_action);
            tvi.IsExpanded = true;

            ContextMenu cm = new System.Windows.Controls.ContextMenu();
            cm.Height = 110;
            cm.Width = 150; 

            MenuItem cm_i = new MenuItem();
            cm_i.Header = "start state";
            cm_i.Tag = newState.name;
            cm_i.AddHandler(MenuItem.ClickEvent, new RoutedEventHandler(start_state_clicked));
            cm_i.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
            cm_i.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
            cm_i.FontSize = 10;
            cm_i.Foreground = Brushes.DarkSeaGreen;

            BitmapImage cm_i_image = new BitmapImage();
            cm_i_image.BeginInit();
            Uri cm_i_Uri = new Uri("/PMisuseAn;component/images/startstate.gif", UriKind.RelativeOrAbsolute);
            cm_i_image.UriSource = cm_i_Uri;
            cm_i_image.EndInit();

            Image cm_i_iconImage = new Image();
            cm_i_iconImage.Source = cm_i_image;

            cm_i.Icon = cm_i_iconImage;

            MenuItem cm_i_e = new MenuItem();
            cm_i_e.Header = "end state";
            cm_i_e.Tag = newState.name;
            cm_i_e.AddHandler(MenuItem.ClickEvent, new RoutedEventHandler(end_state_clicked));
            cm_i_e.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
            cm_i_e.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
            cm_i_e.FontSize = 10;
            cm_i_e.Foreground = Brushes.DarkRed;

            BitmapImage cm_i_e_image = new BitmapImage();
            cm_i_e_image.BeginInit();
            Uri cm_i_e_Uri = new Uri("/PMisuseAn;component/images/stopstate.gif", UriKind.RelativeOrAbsolute);
            cm_i_e_image.UriSource = cm_i_e_Uri;
            cm_i_e_image.EndInit();

            Image cm_i_e_iconImage = new Image();
            cm_i_e_iconImage.Source = cm_i_e_image;

            cm_i_e.Icon = cm_i_e_iconImage;

            //MenuItem cm_mp = new MenuItem();
            //cm_mp.Header = "mitigation point";
            //cm_mp.Tag = newState.name;
            //if (newState.isMitigationPoint == true)
            //{
            //    cm_mp.IsChecked = true;
            //}
            //cm_mp.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(mitigation_point_state_clicked));
            //cm_mp.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(mitigation_point_state_clicked));
            //cm_mp.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
            //cm_mp.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
            //cm_mp.FontSize = 10;
            //cm_mp.Background = Brushes.LightYellow;
            //cm_mp.IsCheckable = true;

            MenuItem cm_mu = new MenuItem();
            cm_mu.Header = "misuse point";
            cm_mu.Tag = newState.name;
            if (newState.isMisusePoint == true)
            {
                cm_mu.IsChecked = true;
            }
            cm_mu.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(misuse_point_state_clicked));
            cm_mu.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(misuse_point_state_clicked));
            cm_mu.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
            cm_mu.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
            cm_mu.FontSize = 10;
           // cm_mu.Background = Brushes.OrangeRed;
            cm_mu.IsCheckable = true;

            MenuItem cm_m_mr = new MenuItem();
            cm_m_mr.Header = "Mitigation references";
            cm_m_mr.Tag = newState.name;
            if (newState.isMisusePoint == false)
            {
                cm_m_mr.IsEnabled = false;
            }
            if (m_ref_s.isEmpty == false)
            {
                cm_m_mr.IsChecked = true;
            }
            cm_m_mr.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(mitigation_references_state_clicked));
            cm_m_mr.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(mitigation_references_state_clicked));
            cm_m_mr.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
            cm_m_mr.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
            cm_m_mr.FontSize = 10;
            //cm_m_act.Background = Brushes.OrangeRed;
            cm_m_mr.IsCheckable = true;

            cm.Items.Add(cm_i);
            cm.Items.Add(cm_i_e);
            //cm.Items.Add(cm_mp);
            cm.Items.Add(cm_mu);
            cm.Items.Add(cm_m_mr);

            tvi.ContextMenu = cm;

            states.Items.Add(tvi);

            newState = new State();
            newState.machineName = machineName_;
            newState.clusterName = MainWindow.clusterName;
            new_ent_name_tb.Text = "";
            new_ent_desc_tb.Text = "";
            
            new_ent_name_tb.Visibility = System.Windows.Visibility.Hidden;
            new_ent_Name_l.Visibility = System.Windows.Visibility.Hidden;
            apply_new_event_b.Visibility = System.Windows.Visibility.Hidden;
            new_ent_desc_tb.Visibility = System.Windows.Visibility.Hidden;
            new_event_ppties_gb.Visibility = System.Windows.Visibility.Hidden;
            desc_l.Visibility = System.Windows.Visibility.Hidden;
            update_event_b.Visibility = System.Windows.Visibility.Hidden;
            delete_event_b.Visibility = System.Windows.Visibility.Hidden;
            define_state_b.Visibility = System.Windows.Visibility.Hidden;
            delete_state_b.Visibility = System.Windows.Visibility.Hidden;
            update_state_b.Visibility = System.Windows.Visibility.Hidden;
            operational_atts_gb.Visibility = System.Windows.Visibility.Hidden;
            state_action_apply_b.Visibility = System.Windows.Visibility.Hidden;
            state_action_update_b.Visibility = System.Windows.Visibility.Hidden;
            state_action_delete_b.Visibility = System.Windows.Visibility.Hidden;
            transitionPolicies_gb.Visibility = System.Windows.Visibility.Hidden;
            update_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            apply_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            start_state_l.Visibility = System.Windows.Visibility.Hidden;
            start_state_cb.Visibility = System.Windows.Visibility.Hidden;
            ass_event_l.Visibility = System.Windows.Visibility.Hidden;
            associated_event_cb.Visibility = System.Windows.Visibility.Hidden;
            end_state_l.Visibility = System.Windows.Visibility.Hidden;
            end_state_cb.Visibility = System.Windows.Visibility.Hidden;
            delete_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            isCallableState_cb.Visibility = System.Windows.Visibility.Hidden;
            isCallableTransition_cb.Visibility = System.Windows.Visibility.Hidden;

            genStateMachineGraph();
        }

        private void update_state_b_Click(object sender, RoutedEventArgs e)
        {

            if (newState == null)
            {
                return;
            }

            string stateName = new_ent_name_tb.Text;
            stateName = stateName.Trim();
            stateName = stateName.TrimEnd('\n');
            stateName = stateName.TrimEnd('\r');

            if (stateName.Count() == 0)
            {
                MessageBoxResult result = MessageBox.Show(this, "NULL state name...",
                            "error", MessageBoxButton.OK,
                            MessageBoxImage.Information);
                return;
            }
            

            if (isStateUpdate == false)
            {
                if (existingState(stateName) == true)
                {
                    MessageBoxResult result = MessageBox.Show(this, stateName + " state already exist...",
                                "Conflict", MessageBoxButton.OK,
                                MessageBoxImage.Information);

                    return;
                }

            }
                        
            newState.name = stateName;
            newState.machineName = machineName_;
            string stateDesc = new_ent_desc_tb.Text;
            newState.description = stateDesc;
            
            if (isCallableState_cb.IsChecked == true)
            {
                newState.isCallable = true;
            }
            else
            {
                newState.isCallable = false;
            }

            //MisUseAnObjectsDB.updateStateDB(newState, MainWindow.clusterName);
            machine_.updateState(newState);
            MisUseAnObjectsDB.addStateMachineDB(machine_, MainWindow.clusterName);

            loadStates();
            loadTransitions();                      

            newState = new State();
            newState.machineName = machineName_;
            newState.clusterName = MainWindow.clusterName;
            new_ent_name_tb.Text = "";
            new_ent_desc_tb.Text = "";

            new_ent_name_tb.Visibility = System.Windows.Visibility.Hidden;
            new_ent_Name_l.Visibility = System.Windows.Visibility.Hidden;
            apply_new_event_b.Visibility = System.Windows.Visibility.Hidden;
            new_ent_desc_tb.Visibility = System.Windows.Visibility.Hidden;
            new_event_ppties_gb.Visibility = System.Windows.Visibility.Hidden;
            desc_l.Visibility = System.Windows.Visibility.Hidden;
            update_event_b.Visibility = System.Windows.Visibility.Hidden;
            delete_event_b.Visibility = System.Windows.Visibility.Hidden;
            define_state_b.Visibility = System.Windows.Visibility.Hidden;
            delete_state_b.Visibility = System.Windows.Visibility.Hidden;
            update_state_b.Visibility = System.Windows.Visibility.Hidden;
            operational_atts_gb.Visibility = System.Windows.Visibility.Hidden;
            state_action_apply_b.Visibility = System.Windows.Visibility.Hidden;
            state_action_update_b.Visibility = System.Windows.Visibility.Hidden;
            state_action_delete_b.Visibility = System.Windows.Visibility.Hidden;
            transitionPolicies_gb.Visibility = System.Windows.Visibility.Hidden;
            update_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            apply_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            start_state_l.Visibility = System.Windows.Visibility.Hidden;
            start_state_cb.Visibility = System.Windows.Visibility.Hidden;
            ass_event_l.Visibility = System.Windows.Visibility.Hidden;
            associated_event_cb.Visibility = System.Windows.Visibility.Hidden;
            end_state_l.Visibility = System.Windows.Visibility.Hidden;
            end_state_cb.Visibility = System.Windows.Visibility.Hidden;
            delete_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            isCallableState_cb.Visibility = System.Windows.Visibility.Hidden;
            isCallableTransition_cb.Visibility = System.Windows.Visibility.Hidden;

            genStateMachineGraph();
        }

        private void delete_state_b_Click(object sender, RoutedEventArgs e)
        {
            string stateName = new_ent_name_tb.Text;
            stateName = stateName.Trim();
            stateName = stateName.TrimEnd('\n');
            stateName = stateName.TrimEnd('\r');

            if (stateName.Count() > 0)
            {
                MessageBoxResult result = MessageBox.Show(this, "confirm delete of " + stateName + " state",
                            "Confirm", MessageBoxButton.YesNo,
                            MessageBoxImage.Information);

                if (result == MessageBoxResult.No)
                {
                    return;
                }
                else
                {
                    //MisUseAnObjectsDB.deleteStateDB(machineName_, stateName, MainWindow.clusterName);
                    
                    if (machine_ != null)
                    {
                        machine_.removeState(stateName);
                    }
                    MisUseAnObjectsDB.addStateMachineDB(machine_, MainWindow.clusterName);

                    allExistingStates = MisUseAnObjectsDB.loadAllStates(machineName_, MainWindow.clusterName);
                    newState = new State();
                    newState.machineName = machineName_;
                    newState.clusterName = MainWindow.clusterName;
                    new_ent_name_tb.Text = "";
                    new_ent_desc_tb.Text = "";
                    
                    new_ent_name_tb.Visibility = System.Windows.Visibility.Hidden;
                    new_ent_Name_l.Visibility = System.Windows.Visibility.Hidden;
                    apply_new_event_b.Visibility = System.Windows.Visibility.Hidden;
                    new_ent_desc_tb.Visibility = System.Windows.Visibility.Hidden;
                    new_event_ppties_gb.Visibility = System.Windows.Visibility.Hidden;
                    desc_l.Visibility = System.Windows.Visibility.Hidden;
                    update_event_b.Visibility = System.Windows.Visibility.Hidden;
                    delete_event_b.Visibility = System.Windows.Visibility.Hidden;
                    delete_state_b.Visibility = System.Windows.Visibility.Hidden;
                    update_state_b.Visibility = System.Windows.Visibility.Hidden;
                    define_state_b.Visibility = System.Windows.Visibility.Hidden;
                    operational_atts_gb.Visibility = System.Windows.Visibility.Hidden;
                    state_action_apply_b.Visibility = System.Windows.Visibility.Hidden;
                    state_action_update_b.Visibility = System.Windows.Visibility.Hidden;
                    state_action_delete_b.Visibility = System.Windows.Visibility.Hidden;
                    transitionPolicies_gb.Visibility = System.Windows.Visibility.Hidden;
                    update_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
                    apply_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
                    start_state_l.Visibility = System.Windows.Visibility.Hidden;
                    start_state_cb.Visibility = System.Windows.Visibility.Hidden;
                    ass_event_l.Visibility = System.Windows.Visibility.Hidden;
                    associated_event_cb.Visibility = System.Windows.Visibility.Hidden;
                    end_state_l.Visibility = System.Windows.Visibility.Hidden;
                    end_state_cb.Visibility = System.Windows.Visibility.Hidden;
                    delete_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
                    isCallableState_cb.Visibility = System.Windows.Visibility.Hidden;
                    isCallableTransition_cb.Visibility = System.Windows.Visibility.Hidden;

                    foreach (TreeViewItem item in states.Items)
                    {
                        if (item.Tag.Equals(stateName))
                        {
                            states.Items.Remove(item);
                            break;
                        }
                    }
                    loadTransitions();
                }
            }

            genStateMachineGraph();
        }

        public void loadAttributesToStateActionOperationalAttributes()
        {
            List<string> agentAttributes_s = new List<string>();
            List<string> functionalAttributes_s = new List<string>();
            List<string> environmentalAttributes_s = new List<string>();

            agentAttributes = MisUseAnObjectsDB.loadAgentAttributes(MainWindow.clusterName);
            //functionalAttributes = MisUseAnObjectsDB.loadFunctionalAttributes(MainWindow.clusterName);
            environmentalAttributes = MisUseAnObjectsDB.loadEnvironmentAttributes(MainWindow.clusterName);

            agentAttributes_lb.Items.Clear();
            //functionalAttributes_lb.Items.Clear();
            environmentAttributes_lb.Items.Clear();

            foreach (Attribute att in agentAttributes)
            {
                agentAttributes_s.Add(att.name);

                bool contained = agentAttributes_lb.Items.Contains(att.name);
                if (contained == false)
                {
                    CheckBox cb = new CheckBox();
                    cb.Tag = att.name;
                    cb.Content = att.name;
                    cb.AddHandler(CheckBox.CheckedEvent, new RoutedEventHandler(state_action_op_att_Checked));
                    cb.AddHandler(CheckBox.UncheckedEvent, new RoutedEventHandler(state_action_op_att_Checked));
                    agentAttributes_lb.Items.Add(cb);
                }
            }

            //foreach (Attribute att in functionalAttributes)
            //{
            //    functionalAttributes_s.Add(att.name);
            //    bool contained = functionalAttributes_lb.Items.Contains(att.name);
            //    if (contained == false)
            //    {
            //        CheckBox cb = new CheckBox();
            //        cb.Tag = att.name;
            //        cb.Content = att.name;
            //        cb.AddHandler(CheckBox.CheckedEvent, new RoutedEventHandler(state_action_op_att_Checked));
            //        cb.AddHandler(CheckBox.UncheckedEvent, new RoutedEventHandler(state_action_op_att_Checked));
            //        functionalAttributes_lb.Items.Add(cb);
            //    }
            //}

            foreach (Attribute att in environmentalAttributes)
            {
                environmentalAttributes_s.Add(att.name);
                bool contained = environmentAttributes_lb.Items.Contains(att.name);
                if (contained == false)
                {
                    CheckBox cb = new CheckBox();
                    cb.Tag = att.name;
                    cb.Content = att.name;
                    cb.AddHandler(CheckBox.CheckedEvent, new RoutedEventHandler(state_action_op_att_Checked));
                    cb.AddHandler(CheckBox.UncheckedEvent, new RoutedEventHandler(state_action_op_att_Checked));
                    environmentAttributes_lb.Items.Add(cb);
                }
            }
        }

        public void loadAttributesToEventOperationalAttributes()
        {
            List<string> agentAttributes_s = new List<string>();
            List<string> functionalAttributes_s = new List<string>();
            List<string> environmentalAttributes_s = new List<string>();

            agentAttributes = MisUseAnObjectsDB.loadAgentAttributes(MainWindow.clusterName);
            //functionalAttributes = MisUseAnObjectsDB.loadFunctionalAttributes(MainWindow.clusterName);
            environmentalAttributes = MisUseAnObjectsDB.loadEnvironmentAttributes(MainWindow.clusterName);

            agentAttributes_lb.Items.Clear();
            //functionalAttributes_lb.Items.Clear();
            environmentAttributes_lb.Items.Clear();

            foreach (Attribute att in agentAttributes)
            {
                agentAttributes_s.Add(att.name);

                bool contained = agentAttributes_lb.Items.Contains(att.name);
                if (contained == false)
                {
                    CheckBox cb = new CheckBox();
                    cb.Tag = att.name;
                    cb.Content = att.name;
                    cb.AddHandler(CheckBox.CheckedEvent, new RoutedEventHandler(event_op_att_Checked));
                    cb.AddHandler(CheckBox.UncheckedEvent, new RoutedEventHandler(event_op_att_Checked));
                    agentAttributes_lb.Items.Add(cb);
                }
            }

            //foreach (Attribute att in functionalAttributes)
            //{
            //    functionalAttributes_s.Add(att.name);
            //    bool contained = functionalAttributes_lb.Items.Contains(att.name);
            //    if (contained == false)
            //    {
            //        CheckBox cb = new CheckBox();
            //        cb.Tag = att.name;
            //        cb.Content = att.name;
            //        cb.AddHandler(CheckBox.CheckedEvent, new RoutedEventHandler(event_op_att_Checked));
            //        cb.AddHandler(CheckBox.UncheckedEvent, new RoutedEventHandler(event_op_att_Checked));
            //        functionalAttributes_lb.Items.Add(cb);
            //    }
            //}

            foreach (Attribute att in environmentalAttributes)
            {
                environmentalAttributes_s.Add(att.name);
                bool contained = environmentAttributes_lb.Items.Contains(att.name);
                if (contained == false)
                {
                    CheckBox cb = new CheckBox();
                    cb.Tag = att.name;
                    cb.Content = att.name;
                    cb.AddHandler(CheckBox.CheckedEvent, new RoutedEventHandler(event_op_att_Checked));
                    cb.AddHandler(CheckBox.UncheckedEvent, new RoutedEventHandler(event_op_att_Checked));
                    environmentAttributes_lb.Items.Add(cb);
                }
            }
        }

        public void reloadAttributesToStateActionOperationalAttributes(List<string> operationalAttributes)
        {

            agentAttributes = MisUseAnObjectsDB.loadAgentAttributes(MainWindow.clusterName);
            //functionalAttributes = MisUseAnObjectsDB.loadFunctionalAttributes(MainWindow.clusterName);
            environmentalAttributes = MisUseAnObjectsDB.loadEnvironmentAttributes(MainWindow.clusterName);

            agentAttributes_lb.Items.Clear();
            //functionalAttributes_lb.Items.Clear();
            environmentAttributes_lb.Items.Clear();

            foreach (Attribute att in agentAttributes)
            {
                bool contained = agentAttributes_lb.Items.Contains(att.name);
                if (contained == false)
                {
                    CheckBox cb = new CheckBox();
                    cb.Tag = att.name;
                    cb.Content = att.name;
                    foreach (string opatt in operationalAttributes)
                    {
                        if (att.name.Equals(opatt))
                        {
                            cb.IsChecked = true;
                            break;
                        }
                    }
                    cb.AddHandler(CheckBox.CheckedEvent, new RoutedEventHandler(state_action_op_att_Checked));
                    cb.AddHandler(CheckBox.UncheckedEvent, new RoutedEventHandler(state_action_op_att_Checked));
                    agentAttributes_lb.Items.Add(cb);
                }
            }

            //foreach (Attribute att in functionalAttributes)
            //{
            //    bool contained = functionalAttributes_lb.Items.Contains(att.name);
            //    if (contained == false)
            //    {
            //        CheckBox cb = new CheckBox();
            //        cb.Tag = att.name;
            //        cb.Content = att.name;
            //        foreach (string opatt in operationalAttributes)
            //        {
            //            if (att.name.Equals(opatt))
            //            {
            //                cb.IsChecked = true;
            //                break;
            //            }
            //        }
            //        cb.AddHandler(CheckBox.CheckedEvent, new RoutedEventHandler(state_action_op_att_Checked));
            //        cb.AddHandler(CheckBox.UncheckedEvent, new RoutedEventHandler(state_action_op_att_Checked));
            //        functionalAttributes_lb.Items.Add(cb);
            //    }
            //}

            foreach (Attribute att in environmentalAttributes)
            {
                bool contained = environmentAttributes_lb.Items.Contains(att.name);
                if (contained == false)
                {
                    CheckBox cb = new CheckBox();
                    cb.Tag = att.name;
                    cb.Content = att.name;
                    foreach (string opatt in operationalAttributes)
                    {
                        if (att.name.Equals(opatt))
                        {
                            cb.IsChecked = true;
                            break;
                        }
                    }
                    cb.AddHandler(CheckBox.CheckedEvent, new RoutedEventHandler(state_action_op_att_Checked));
                    cb.AddHandler(CheckBox.UncheckedEvent, new RoutedEventHandler(state_action_op_att_Checked));
                    environmentAttributes_lb.Items.Add(cb);
                }
            }
        }

        public void reloadAttributesToEventOperationalAttributes(List<string> operationalAttributes)
        {

            agentAttributes = MisUseAnObjectsDB.loadAgentAttributes(MainWindow.clusterName);
            //functionalAttributes = MisUseAnObjectsDB.loadFunctionalAttributes(MainWindow.clusterName);
            environmentalAttributes = MisUseAnObjectsDB.loadEnvironmentAttributes(MainWindow.clusterName);

            agentAttributes_lb.Items.Clear();
            //functionalAttributes_lb.Items.Clear();
            environmentAttributes_lb.Items.Clear();

            foreach (Attribute att in agentAttributes)
            {
                bool contained = agentAttributes_lb.Items.Contains(att.name);
                if (contained == false)
                {
                    CheckBox cb = new CheckBox();
                    cb.Tag = att.name;
                    cb.Content = att.name;
                    foreach (string opatt in operationalAttributes)
                    {
                        if (att.name.Equals(opatt))
                        {
                            cb.IsChecked = true;
                            break;
                        }
                    }
                    cb.AddHandler(CheckBox.CheckedEvent, new RoutedEventHandler(event_op_att_Checked));
                    cb.AddHandler(CheckBox.UncheckedEvent, new RoutedEventHandler(event_op_att_Checked));
                    agentAttributes_lb.Items.Add(cb);
                }
            }

            //foreach (Attribute att in functionalAttributes)
            //{
            //    bool contained = functionalAttributes_lb.Items.Contains(att.name);
            //    if (contained == false)
            //    {
            //        CheckBox cb = new CheckBox();
            //        cb.Tag = att.name;
            //        cb.Content = att.name;
            //        foreach (string opatt in operationalAttributes)
            //        {
            //            if (att.name.Equals(opatt))
            //            {
            //                cb.IsChecked = true;
            //                break;
            //            }
            //        }
            //        cb.AddHandler(CheckBox.CheckedEvent, new RoutedEventHandler(event_op_att_Checked));
            //        cb.AddHandler(CheckBox.UncheckedEvent, new RoutedEventHandler(event_op_att_Checked));
            //        functionalAttributes_lb.Items.Add(cb);
            //    }
            //}

            foreach (Attribute att in environmentalAttributes)
            {
                bool contained = environmentAttributes_lb.Items.Contains(att.name);
                if (contained == false)
                {
                    CheckBox cb = new CheckBox();
                    cb.Tag = att.name;
                    cb.Content = att.name;
                    foreach (string opatt in operationalAttributes)
                    {
                        if (att.name.Equals(opatt))
                        {
                            cb.IsChecked = true;
                            break;
                        }
                    }
                    cb.AddHandler(CheckBox.CheckedEvent, new RoutedEventHandler(event_op_att_Checked));
                    cb.AddHandler(CheckBox.UncheckedEvent, new RoutedEventHandler(event_op_att_Checked));
                    environmentAttributes_lb.Items.Add(cb);
                }
            }
        }

        private void state_action_delete_b_Click(object sender, RoutedEventArgs e)
        {
            string actionName = new_ent_name_tb.Text;
            actionName = actionName.Trim();
            actionName = actionName.TrimEnd('\n');
            actionName = actionName.TrimEnd('\r');

            if (actionName.Count() > 0)
            {
                MessageBoxResult result = MessageBox.Show(this, "confirm delete of " + actionName + " action",
                            "Confirm", MessageBoxButton.YesNo,
                            MessageBoxImage.Information);

                if (result == MessageBoxResult.No)
                {
                    return;
                }
                else
                {
                    //MisUseAnObjectsDB.deleteStateActionDB(machineName_, stateName_, actionName, MainWindow.clusterName);
                    if (newState != null)
                    {
                        newState.removeAction(actionName);
                    }
                    machine_.removeStateAction(stateName_, actionName);
                    MisUseAnObjectsDB.addStateMachineDB(machine_, MainWindow.clusterName);

                    allExistingStateActions = MisUseAnObjectsDB.loadAllStateActions(machineName_, stateName_, MainWindow.clusterName);
                    newAction = new PMisuseAn.behaviour.model.Action();
                    newAction.machineName = machineName_;
                    newAction.clusterName = MainWindow.clusterName;
                    new_ent_name_tb.Text = "";
                    new_ent_desc_tb.Text = "";

                    new_ent_name_tb.Visibility = System.Windows.Visibility.Hidden;
                    new_ent_Name_l.Visibility = System.Windows.Visibility.Hidden;
                    apply_new_event_b.Visibility = System.Windows.Visibility.Hidden;
                    new_ent_desc_tb.Visibility = System.Windows.Visibility.Hidden;
                    new_event_ppties_gb.Visibility = System.Windows.Visibility.Hidden;
                    desc_l.Visibility = System.Windows.Visibility.Hidden;
                    update_event_b.Visibility = System.Windows.Visibility.Hidden;
                    delete_event_b.Visibility = System.Windows.Visibility.Hidden;
                    delete_state_b.Visibility = System.Windows.Visibility.Hidden;
                    update_state_b.Visibility = System.Windows.Visibility.Hidden;
                    define_state_b.Visibility = System.Windows.Visibility.Hidden;
                    operational_atts_gb.Visibility = System.Windows.Visibility.Hidden;
                    state_action_apply_b.Visibility = System.Windows.Visibility.Hidden;
                    state_action_update_b.Visibility = System.Windows.Visibility.Hidden;
                    state_action_delete_b.Visibility = System.Windows.Visibility.Hidden;
                    transitionPolicies_gb.Visibility = System.Windows.Visibility.Hidden;
                    update_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
                    apply_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
                    start_state_l.Visibility = System.Windows.Visibility.Hidden;
                    start_state_cb.Visibility = System.Windows.Visibility.Hidden;
                    ass_event_l.Visibility = System.Windows.Visibility.Hidden;
                    associated_event_cb.Visibility = System.Windows.Visibility.Hidden;
                    end_state_l.Visibility = System.Windows.Visibility.Hidden;
                    end_state_cb.Visibility = System.Windows.Visibility.Hidden;
                    delete_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
                    isCallableState_cb.Visibility = System.Windows.Visibility.Hidden;
                    isCallableTransition_cb.Visibility = System.Windows.Visibility.Hidden;

                    foreach (TreeViewItem item in stateActionSelected_tv.Items)
                    {
                        string tag_id = (string)item.Tag;
                        string[] tag_split = tag_id.Split(',');

                        string actname = tag_split[0];
                        string staname = tag_split[1];

                        if (actname.Equals(actionName))
                        {
                            stateActionSelected_tv.Items.Remove(item);
                            break;
                        }
                    }
                }
            }            
        }

        private void state_action_update_b_Click(object sender, RoutedEventArgs e)
        {
            string actionName = new_ent_name_tb.Text;
            actionName = actionName.Trim();
            actionName = actionName.TrimEnd('\n');
            actionName = actionName.TrimEnd('\r');

            if (actionName.Count() == 0)
            {
                MessageBoxResult result = MessageBox.Show(this, "State action name required",
                            "error", MessageBoxButton.OK,
                            MessageBoxImage.Information);
                return;
            }

            if (isStateActionUpdate == false)
            {
                if (existingStateAction(stateName_, actionName) == true)
                {
                    MessageBoxResult result = MessageBox.Show(this, actionName + " action already exist in associating state.",
                                "Conflict", MessageBoxButton.OK,
                                MessageBoxImage.Information);

                    return;
                }
            }

            if (newAction == null)
            {
                newAction = new PMisuseAn.behaviour.model.Action();
                newAction.clusterName = MainWindow.clusterName;
            }

            newAction.name = actionName;
            newAction.stateName = stateName_;
            newAction.machineName = machineName_;
            string actionDesc = new_ent_desc_tb.Text;
            newAction.description = actionDesc;

            //MisUseAnObjectsDB.updateStateActionDB(newAction, MainWindow.clusterName);
            machine_.updateStateAction(newAction);
            MisUseAnObjectsDB.addStateMachineDB(machine_, MainWindow.clusterName);

            TreeViewItem item_action = new TreeViewItem();
            item_action.Header = newAction.name;
            item_action.Tag = newAction.name + "," + stateName_;
            item_action.AddHandler(TreeViewItem.SelectedEvent, new RoutedEventHandler(state_action_TreeViewItem_Selected));
            
            bool exist = false;
            foreach (TreeViewItem etv in stateActionSelected_tv.Items)
            {
                string tag_etv = (string)etv.Tag;
                if (tag_etv.Equals((string)item_action.Tag))
                {
                    exist = true;
                }
            }
            if (exist == false)
            {
                stateActionSelected_tv.Items.Add(item_action);
                stateActionSelected_tv.IsExpanded = true;
            } 

            newAction = new PMisuseAn.behaviour.model.Action();
            newAction.machineName = machineName_;
            newAction.clusterName = MainWindow.clusterName;
            new_ent_name_tb.Text = "";
            new_ent_desc_tb.Text = "";

            new_ent_name_tb.Visibility = System.Windows.Visibility.Hidden;
            new_ent_Name_l.Visibility = System.Windows.Visibility.Hidden;
            apply_new_event_b.Visibility = System.Windows.Visibility.Hidden;
            new_ent_desc_tb.Visibility = System.Windows.Visibility.Hidden;
            new_event_ppties_gb.Visibility = System.Windows.Visibility.Hidden;
            desc_l.Visibility = System.Windows.Visibility.Hidden;
            update_event_b.Visibility = System.Windows.Visibility.Hidden;
            delete_event_b.Visibility = System.Windows.Visibility.Hidden;
            define_state_b.Visibility = System.Windows.Visibility.Hidden;
            delete_state_b.Visibility = System.Windows.Visibility.Hidden;
            update_state_b.Visibility = System.Windows.Visibility.Hidden;
            operational_atts_gb.Visibility = System.Windows.Visibility.Hidden;
            state_action_apply_b.Visibility = System.Windows.Visibility.Hidden;
            state_action_update_b.Visibility = System.Windows.Visibility.Hidden;
            state_action_delete_b.Visibility = System.Windows.Visibility.Hidden;
            transitionPolicies_gb.Visibility = System.Windows.Visibility.Hidden;
            update_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            apply_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            start_state_l.Visibility = System.Windows.Visibility.Hidden;
            start_state_cb.Visibility = System.Windows.Visibility.Hidden;
            ass_event_l.Visibility = System.Windows.Visibility.Hidden;
            associated_event_cb.Visibility = System.Windows.Visibility.Hidden;
            end_state_l.Visibility = System.Windows.Visibility.Hidden;
            end_state_cb.Visibility = System.Windows.Visibility.Hidden;
            delete_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            isCallableState_cb.Visibility = System.Windows.Visibility.Hidden;
            isCallableTransition_cb.Visibility = System.Windows.Visibility.Hidden;
        }

        private void state_action_apply_b_Click(object sender, RoutedEventArgs e)
        {
            string actionName = new_ent_name_tb.Text;
            actionName = actionName.Trim();
            actionName = actionName.TrimEnd('\n');
            actionName = actionName.TrimEnd('\r');

            if (actionName.Count() == 0)
            {
                MessageBoxResult result = MessageBox.Show(this, "State action name required",
                            "error", MessageBoxButton.OK,
                            MessageBoxImage.Information);
                return;
            }


            if (isStateActionUpdate == false)
            {
                if (existingStateAction(stateName_, actionName) == true)
                {
                    MessageBoxResult result = MessageBox.Show(this, actionName + " action already exist in associating state.",
                                "Conflict", MessageBoxButton.OK,
                                MessageBoxImage.Information);

                    return;
                }
            }

            if (newAction == null)
            {
                newAction = new PMisuseAn.behaviour.model.Action();
                newAction.clusterName = MainWindow.clusterName;
            }

            newAction.name = actionName;
            newAction.stateName = stateName_;
            newAction.machineName = machineName_;
            string actionDesc = new_ent_desc_tb.Text;
            newAction.description = actionDesc;

            //MisUseAnObjectsDB.addStateActionDB(newAction, MainWindow.clusterName);
            machine_.addStateAction(newAction);
            MisUseAnObjectsDB.addStateMachineDB(machine_, MainWindow.clusterName);

           
            TreeViewItem item_action = new TreeViewItem();
            item_action.Header = newAction.name;
            item_action.Tag = newAction.name+"," + stateName_;
            item_action.AddHandler(TreeViewItem.SelectedEvent, new RoutedEventHandler(state_action_TreeViewItem_Selected));
                     
            //if (newAction.isMitigationPoint == true)
            //{
            //    item_action.Background = Brushes.LightYellow;
            //}
            if (newAction.isMisusePoint == true)
            {
                item_action.Background = Brushes.OrangeRed;
            }
            MitigationReferences m_ref = MisUseAnObjectsDB.loadStateActionMitigationReferencesDB(newAction.name, stateName_, machineName_, MainWindow.clusterName);

            if (m_ref.isEmpty == false)
            {
                item_action.Background = Brushes.Green;
            }
            ContextMenu cm_act = new System.Windows.Controls.ContextMenu();
            cm_act.Height = 60;
            cm_act.Width = 150;


            //MenuItem cm_mp_act = new MenuItem();
            //cm_mp_act.Header = "mitigation point";
            //cm_mp_act.Tag = newAction.name + "," + stateName_;
            //if (newAction.isMitigationPoint == true)
            //{
            //    cm_mp_act.IsChecked = true;
            //}
            //cm_mp_act.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(mitigation_point_state_action_clicked));
            //cm_mp_act.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(mitigation_point_state_action_clicked));
            //cm_mp_act.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
            //cm_mp_act.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
            //cm_mp_act.FontSize = 10;
            //cm_mp_act.Background = Brushes.LightYellow;
            //cm_mp_act.IsCheckable = true;

            MenuItem cm_mu_act = new MenuItem();
            cm_mu_act.Header = "misuse point";
            cm_mu_act.Tag = newAction.name + "," + stateName_;
            if (newAction.isMisusePoint == true)
            {
                cm_mu_act.IsChecked = true;
            }
            cm_mu_act.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(misuse_point_state_action_clicked));
            cm_mu_act.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(misuse_point_state_action_clicked));
            cm_mu_act.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
            cm_mu_act.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
            cm_mu_act.FontSize = 10;
            //cm_mu_act.Background = Brushes.OrangeRed;
            cm_mu_act.IsCheckable = true;

            MenuItem cm_m_act = new MenuItem();
            cm_m_act.Header = "Mitigation references";
            cm_m_act.Tag = newAction.name + "," + stateName_;
            if (newAction.isMisusePoint == false)
            {
                cm_m_act.IsEnabled = false;
            }
            if (m_ref.isEmpty == false)
            {
                cm_m_act.IsChecked = true;
            }
            cm_m_act.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(mitigation_references_state_action_clicked));
            cm_m_act.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(mitigation_references_state_action_clicked));
            cm_m_act.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
            cm_m_act.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
            cm_m_act.FontSize = 10;
            //cm_m_act.Background = Brushes.OrangeRed;
            cm_m_act.IsCheckable = true;

            //cm_act.Items.Add(cm_mp_act);
            cm_act.Items.Add(cm_mu_act);
            cm_act.Items.Add(cm_m_act);

            item_action.ContextMenu = cm_act;
            
            bool exist = false;
            foreach (TreeViewItem etv in stateActionSelected_tv.Items)
            {
                string tag_etv = (string)etv.Tag;
                if (tag_etv.Equals((string)item_action.Tag))
                {
                    exist = true;
                }
            }
            if (exist == false)
            {
                stateActionSelected_tv.Items.Add(item_action);
                stateActionSelected_tv.IsExpanded = true;
            } 

            newAction = new PMisuseAn.behaviour.model.Action();
            newAction.machineName = machineName_;
            newAction.clusterName = MainWindow.clusterName;
            new_ent_name_tb.Text = "";
            new_ent_desc_tb.Text = "";

            new_ent_name_tb.Visibility = System.Windows.Visibility.Hidden;
            new_ent_Name_l.Visibility = System.Windows.Visibility.Hidden;
            apply_new_event_b.Visibility = System.Windows.Visibility.Hidden;
            new_ent_desc_tb.Visibility = System.Windows.Visibility.Hidden;
            new_event_ppties_gb.Visibility = System.Windows.Visibility.Hidden;
            desc_l.Visibility = System.Windows.Visibility.Hidden;
            update_event_b.Visibility = System.Windows.Visibility.Hidden;
            delete_event_b.Visibility = System.Windows.Visibility.Hidden;
            define_state_b.Visibility = System.Windows.Visibility.Hidden;
            delete_state_b.Visibility = System.Windows.Visibility.Hidden;
            update_state_b.Visibility = System.Windows.Visibility.Hidden;
            operational_atts_gb.Visibility = System.Windows.Visibility.Hidden;
            state_action_apply_b.Visibility = System.Windows.Visibility.Hidden;
            state_action_update_b.Visibility = System.Windows.Visibility.Hidden;
            state_action_delete_b.Visibility = System.Windows.Visibility.Hidden;
            transitionPolicies_gb.Visibility = System.Windows.Visibility.Hidden;
            update_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            apply_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            start_state_l.Visibility = System.Windows.Visibility.Hidden;
            start_state_cb.Visibility = System.Windows.Visibility.Hidden;
            ass_event_l.Visibility = System.Windows.Visibility.Hidden;
            associated_event_cb.Visibility = System.Windows.Visibility.Hidden;
            end_state_l.Visibility = System.Windows.Visibility.Hidden;
            end_state_cb.Visibility = System.Windows.Visibility.Hidden;
            delete_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            isCallableState_cb.Visibility = System.Windows.Visibility.Hidden;
            isCallableTransition_cb.Visibility = System.Windows.Visibility.Hidden;
        }

        CheckBox donillcb;
        List<Policy> policy_statements;

        private void loadStateTransitionsPolicyStatementList(Transition c_transition)
        {
            int stat_no = 1;
            policy_statements = MisUseAnObjectsDB.loadAllPolicyStatementsFull(MainWindow.clusterName);

            if (policy_statements != null)
            {
                transition_policies_lb.Items.Clear();

                string assEventName = c_transition.associatedEevent;
                PolicyStatementAnalyser psa = new PolicyStatementAnalyser();

                foreach (Policy p_stat in policy_statements)
                {
                    ListBoxItem l = new ListBoxItem();
                    StackPanel s = new StackPanel();
                    s.Orientation = System.Windows.Controls.Orientation.Horizontal;
                    ContentPresenter c1 = new ContentPresenter();
                    c1.Content = stat_no;
                    stat_no = stat_no + 1;

                    CheckBox cb = new CheckBox();
                    cb.Tag = p_stat.id;
                    cb.Content = p_stat.statement;

                    if (assEventName != null)
                    {
                        Event activeEvent = null;
                        foreach (Event eva in machine_.events)
                        {
                            if (eva.name.Equals(assEventName))
                            {
                                activeEvent = eva;
                                break;
                            }
                        }
                        if(activeEvent != null)
                        {
                            foreach (string opAttribute in activeEvent.operationalAttributes_)
                            {
                                psa.ifThenUnlessTokenisation(p_stat.statement);
                                Attribute att = psa.getIfAttribute();
                                if (att != null && att.name.Equals(opAttribute))
                                {
                                    cb.IsChecked = true;
                                    break;
                                }
                            }
                        }
                        
                    }
                    cb.IsEnabled = false; 
                    cb.AddHandler(CheckBox.CheckedEvent, new RoutedEventHandler(transition_policy_Checked));
                    cb.AddHandler(CheckBox.UncheckedEvent, new RoutedEventHandler(transition_policy_Checked));
                    ContentPresenter c2 = new ContentPresenter();
                    c2.Content = cb;
                    c1.Width = 15;
                    c2.Width = transition_policies_lb.Width - 25;
                    s.Children.Add(c1);
                    s.Children.Add(c2);
                    l.Content = s;

                    if (p_stat.statement.Equals("DO[NILL]"))
                    {
                        donillcb = cb;
                        cb.IsChecked = true;
                        donillcb.IsEnabled = false;
                        transition_policies_lb.Items.Insert(0, l);
                    }
                    else
                        transition_policies_lb.Items.Add(l); 
                }
            }
        }

        private void reloadStateTransitionsPolicyStatementList(Transition c_transition)
        {
            int stat_no = 1;
            policy_statements = MisUseAnObjectsDB.loadAllPolicyStatementsFull(MainWindow.clusterName);

            if (policy_statements != null)
            {
                transition_policies_lb.Items.Clear();

                string assEventName = c_transition.associatedEevent;
                PolicyStatementAnalyser psa = new PolicyStatementAnalyser();

                foreach (Policy p_stat in policy_statements)
                {
                    ListBoxItem l = new ListBoxItem();
                    StackPanel s = new StackPanel();
                    s.Orientation = System.Windows.Controls.Orientation.Horizontal;
                    ContentPresenter c1 = new ContentPresenter();
                    c1.Content = stat_no;
                    stat_no = stat_no + 1;

                    CheckBox cb = new CheckBox();
                    cb.Tag = p_stat.id;
                    cb.Content = p_stat.statement;

                    if (assEventName != null)
                    {
                        Event activeEvent = null;
                        foreach (Event eva in machine_.events)
                        {
                            if (eva.name.Equals(assEventName))
                            {
                                activeEvent = eva;
                                break;
                            }
                        }
                        if (activeEvent != null)
                        {
                            foreach (string opAttribute in activeEvent.operationalAttributes_)
                            {
                                psa.ifThenUnlessTokenisation(p_stat.statement);
                                Attribute att = psa.getIfAttribute();
                                if (att != null && att.name.Equals(opAttribute))
                                {
                                    cb.IsChecked = true;
                                    break;
                                }
                            }
                        }

                    }                   
                    //foreach (string pid in policyIDs)
                    //{
                    //    if (p_stat.id.Equals(pid))
                    //    {
                    //        cb.IsChecked = true;
                    //        break;
                    //    }
                    //}
                    cb.IsEnabled = false; 

                    cb.AddHandler(CheckBox.CheckedEvent, new RoutedEventHandler(transition_policy_Checked));
                    cb.AddHandler(CheckBox.UncheckedEvent, new RoutedEventHandler(transition_policy_Checked));
                    //cb.IsEnabled = false;
                    ContentPresenter c2 = new ContentPresenter();
                    c2.Content = cb;
                    c1.Width = 15;
                    c2.Width = transition_policies_lb.Width - 25;
                    s.Children.Add(c1);
                    s.Children.Add(c2);
                    l.Content = s;

                    if (p_stat.statement.Equals("DO[NILL]"))
                    {
                        donillcb = cb;
                        donillcb.IsEnabled = false;
                        //cb.IsChecked = true;
                        transition_policies_lb.Items.Insert(0, l);
                    }
                    else
                        transition_policies_lb.Items.Add(l); 
                }
            }
        }


        private void reloadStateTransitionsPolicyStatementList_ass_event_cb_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            int stat_no = 1;
            policy_statements = MisUseAnObjectsDB.loadAllPolicyStatementsFull(MainWindow.clusterName);

            if (policy_statements != null)
            {
                transition_policies_lb.Items.Clear();

                string assEventName = associated_event_cb.Text;
                PolicyStatementAnalyser psa = new PolicyStatementAnalyser();

                foreach (Policy p_stat in policy_statements)
                {
                    ListBoxItem l = new ListBoxItem();
                    StackPanel s = new StackPanel();
                    s.Orientation = System.Windows.Controls.Orientation.Horizontal;
                    ContentPresenter c1 = new ContentPresenter();
                    c1.Content = stat_no;
                    stat_no = stat_no + 1;

                    CheckBox cb = new CheckBox();
                    cb.Tag = p_stat.id;
                    cb.Content = p_stat.statement;

                    if (assEventName != null)
                    {
                        Event activeEvent = null;
                        foreach (Event eva in machine_.events)
                        {
                            if (eva.name.Equals(assEventName))
                            {
                                activeEvent = eva;
                                break;
                            }
                        }
                        if (activeEvent != null)
                        {
                            foreach (string opAttribute in activeEvent.operationalAttributes_)
                            {
                                psa.ifThenUnlessTokenisation(p_stat.statement);
                                Attribute att = psa.getIfAttribute();
                                if (att != null && att.name.Equals(opAttribute))
                                {
                                    cb.IsChecked = true;
                                    break;
                                }
                            }
                        }

                    }
                    //foreach (string pid in policyIDs)
                    //{
                    //    if (p_stat.id.Equals(pid))
                    //    {
                    //        cb.IsChecked = true;
                    //        break;
                    //    }
                    //}
                    cb.IsEnabled = false;

                    cb.AddHandler(CheckBox.CheckedEvent, new RoutedEventHandler(transition_policy_Checked));
                    cb.AddHandler(CheckBox.UncheckedEvent, new RoutedEventHandler(transition_policy_Checked));
                    //cb.IsEnabled = false;
                    ContentPresenter c2 = new ContentPresenter();
                    c2.Content = cb;
                    c1.Width = 15;
                    c2.Width = transition_policies_lb.Width - 25;
                    s.Children.Add(c1);
                    s.Children.Add(c2);
                    l.Content = s;

                    if (p_stat.statement.Equals("DO[NILL]"))
                    {
                        donillcb = cb;
                        donillcb.IsEnabled = false;
                        //cb.IsChecked = true;
                        transition_policies_lb.Items.Insert(0, l);
                    }
                    else
                        transition_policies_lb.Items.Add(l);
                }
            }
        }

        bool existingStateTransition(string transitionName, string startState, string endState, string assEventName, int policyID)
        {
            bool exist = false;

            if (allExistingStateTransitions == null)
            {
                allExistingStateTransitions = MisUseAnObjectsDB.loadAllStateTransitions(machineName_, MainWindow.clusterName);
            }
            foreach (Transition eve in allExistingStateTransitions)
            {
                if (eve.machineName.Equals(machineName_)
                        && eve.transitionName.Equals(transitionName)
                        && eve.startState.Equals(startState)
                        && eve.endState.Equals(endState)
                        && eve.associatedEevent.Equals(assEventName))
                {
                    foreach (string p in eve.policyIDs)
                    {
                        if (p.Equals(policyID))
                        {
                            exist = true;
                            break;
                        }
                    }                    
                }                
            }
            return exist;
        }

        //bool existingStateTransition(string transitionName, string startState, string endState, string assEventName)
        //{
        //    bool exist = false;

        //    if (allExistingStateTransitions == null)
        //    {
        //        allExistingStateTransitions = MisUseAnObjectsDB.loadAllStateTransitions(machineName_, MainWindow.clusterName);
        //    }
        //    foreach (Transition eve in allExistingStateTransitions)
        //    {
        //        if (eve.machineName.Equals(machineName_)
        //                && eve.transitionName.Equals(transitionName)
        //                && eve.startState.Equals(startState)
        //                && eve.endState.Equals(endState)
        //                && eve.associatedEevent.Equals(assEventName))
        //        {
        //            exist = true;
        //            break;
        //        }
        //    }
        //    return exist;
        //}

        bool existingStateTransition(string transitionName)
        {
            bool exist = false;

            if (allExistingStateTransitions == null)
            {
                //allExistingStateTransitions = MisUseAnObjectsDB.loadAllStateTransitions(machineName_, MainWindow.clusterName);
                allExistingStateTransitions = machine_.transitions;
            }
            foreach (Transition eve in allExistingStateTransitions)
            {
                if (eve.machineName.Equals(machineName_)
                        && eve.transitionName.Equals(transitionName))
                {
                    exist = true;
                    break;
                }
            }
            return exist;
        }

        bool f_empty_p = false;
        bool f_cont_p = false;
        private void transition_policy_Checked(object sender, RoutedEventArgs e)
        {
            CheckBox d_cb = (CheckBox)sender;
            string policyID = (string)d_cb.Tag;
                       
            if (newStateTransition == null)
            {
                newStateTransition = new Transition();
                newStateTransition.machineName = machineName_;
            }

            if (newStateTransition.policyIDs.Contains(policyID))
            {
                newStateTransition.removePolicyPD(policyID);
            }
            else
            {
                newStateTransition.addPolicyID(policyID);
            }


            if (newStateTransition.policyIDs.Count() == 0)
            {
                if (f_empty_p == false)
                {
                    f_empty_p = true;
                    donillcb.IsEnabled = false;
                    donillcb.IsChecked = true;

                }               
            }

            if (!d_cb.Content.Equals("DO[NILL]"))
            {
                f_cont_p = false;
                f_empty_p = false;
                donillcb.IsChecked = false;
                donillcb.IsEnabled = false;
            }
            else if (d_cb.Content.Equals("DO[NILL]") && newStateTransition.policyIDs.Count() > 0)
            {                
                if (f_cont_p == false)
                {
                    f_cont_p = true;
                    foreach (Policy p in policy_statements)
                    {
                        if (p.statement.Equals("DO[NILL]"))
                        {
                            if (newStateTransition.policyIDs.Count() > 1)
                            {
                                newStateTransition.policyIDs.Remove(p.id);
                                donillcb.IsEnabled = false;
                                donillcb.IsChecked = false;
                                break;
                            }
                        }
                    }                    
                }                             
            }            
        }
        private void apply_new_state_transition_b_Click(object sender, RoutedEventArgs e)
        {
            string transitionName = new_ent_name_tb.Text;
            transitionName = transitionName.Trim();
            transitionName = transitionName.TrimEnd('\n');
            transitionName = transitionName.TrimEnd('\r');

            string startState = start_state_cb.Text;
            string endState = end_state_cb.Text;
            string associatedEvent = associated_event_cb.Text;

            if (transitionName.Count() == 0)
            {
                MessageBoxResult result = MessageBox.Show(this, "Transition name field is empty",
                            "error", MessageBoxButton.OK,
                            MessageBoxImage.Information);
                return;
            }
            else if (startState.Count() == 0)
            {
                MessageBoxResult result = MessageBox.Show(this, "start state field is empty",
                            "error", MessageBoxButton.OK,
                            MessageBoxImage.Information);
                return;
            }
            else if (endState.Count() == 0)
            {
                MessageBoxResult result = MessageBox.Show(this, "end state field is empty",
                            "error", MessageBoxButton.OK,
                            MessageBoxImage.Information);
                return;
            }
            else if (associatedEvent.Count() == 0)
            {
                MessageBoxResult result = MessageBox.Show(this, "associated event field is empty",
                            "error", MessageBoxButton.OK,
                            MessageBoxImage.Information);
                return;
            }

            //if (existingStateTransition(transitionName, startState, endState, associatedEvent))
            if (existingStateTransition(transitionName))
            {
                MessageBoxResult result = MessageBox.Show(this, transitionName + " already exist",
                                            "error", MessageBoxButton.OK,
                                            MessageBoxImage.Information);
                return;
            }

            if (newStateTransition == null)
            {
                newStateTransition = new Transition();
                newStateTransition.machineName = machineName_;
                newStateTransition.clusterName = MainWindow.clusterName;
            }
            newStateTransition.transitionName = transitionName;
            newStateTransition.startState = startState;
            newStateTransition.endState = endState;
            newStateTransition.associatedEevent = associatedEvent;
            
            if (isCallableTransition_cb.IsChecked == true)
            {
                newStateTransition.isCallable = true;
            }
            else
            {
                newStateTransition.isCallable = false;
            }

            //MisUseAnObjectsDB.addStateTransitionDB(newStateTransition, MainWindow.clusterName);
            machine_.addStateTransition(newStateTransition);
            MisUseAnObjectsDB.addStateMachineDB(machine_, MainWindow.clusterName);

            string trans_tag = newStateTransition.transitionName + "," + newStateTransition.machineName + "," + newStateTransition.startState +
                    "," + newStateTransition.endState + "," + newStateTransition.associatedEevent;
            string trans_content = newStateTransition.transitionName + "(" + newStateTransition.startState +
                "," + newStateTransition.endState + "," + newStateTransition.associatedEevent + ")";
            if (!transitions.Items.Contains(trans_content))
            {
                TreeViewItem item = new TreeViewItem();
                item.Header = trans_content;
                item.Tag = trans_tag;
                item.AddHandler(TreeViewItem.SelectedEvent, new RoutedEventHandler(transition_TreeViewItem_Selected));

                //if (newStateTransition.isMitigationPoint == true)
                //{
                //    item.Background = Brushes.LightYellow;
                //}
                if (newStateTransition.isMisusePoint == true)
                {
                    item.Background = Brushes.OrangeRed;
                }

                MitigationReferences m_ref_s = MisUseAnObjectsDB.loadTransitionMitigationReferencesDB(newStateTransition.transitionName, machineName_, MainWindow.clusterName);

                if (m_ref_s.isEmpty == false)
                {
                    item.Background = Brushes.Green;
                }

                ContextMenu cm_trans = new System.Windows.Controls.ContextMenu();
                cm_trans.Height = 60;
                cm_trans.Width = 150;

                //MenuItem cm_mp_trans = new MenuItem();
                //cm_mp_trans.Header = "mitigation point";
                //cm_mp_trans.Tag = trans_tag;
                //if (newStateTransition.isMitigationPoint == true)
                //{
                //    cm_mp_trans.IsChecked = true;
                //}
                //cm_mp_trans.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(mitigation_point_transition_clicked));
                //cm_mp_trans.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(mitigation_point_transition_clicked));
                //cm_mp_trans.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                //cm_mp_trans.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                //cm_mp_trans.FontSize = 10;
                //cm_mp_trans.Background = Brushes.LightYellow;
                //cm_mp_trans.IsCheckable = true;

                MenuItem cm_mu_trans = new MenuItem();
                cm_mu_trans.Header = "misuse point";
                cm_mu_trans.Tag = trans_tag;
                if (newStateTransition.isMisusePoint == true)
                {
                    cm_mu_trans.IsChecked = true;
                }
                cm_mu_trans.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(misuse_point_transition_clicked));
                cm_mu_trans.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(misuse_point_transition_clicked));
                cm_mu_trans.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                cm_mu_trans.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                cm_mu_trans.FontSize = 10;
                //cm_mu_trans.Background = Brushes.OrangeRed;
                cm_mu_trans.IsCheckable = true;

                MenuItem cm_m_mr = new MenuItem();
                cm_m_mr.Header = "Mitigation references";
                cm_m_mr.Tag = trans_tag;

                if (newStateTransition.isMisusePoint == false)
                {
                    cm_m_mr.IsEnabled = false;
                }
                if (m_ref_s.isEmpty == false)
                {
                    cm_m_mr.IsChecked = true;
                }
                cm_m_mr.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(mitigation_references_transition_clicked));
                cm_m_mr.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(mitigation_references_transition_clicked));
                cm_m_mr.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                cm_m_mr.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                cm_m_mr.FontSize = 10;
                //cm_m_act.Background = Brushes.OrangeRed;
                cm_m_mr.IsCheckable = true;

                //cm_trans.Items.Add(cm_mp_trans);
                cm_trans.Items.Add(cm_mu_trans);
                cm_trans.Items.Add(cm_m_mr);

                item.ContextMenu = cm_trans;
                transitions.Items.Add(item);
            }

            newStateTransition = new Transition();
            newStateTransition.machineName = machineName_;
            newStateTransition.clusterName = MainWindow.clusterName;
            new_ent_name_tb.Text = "";
            start_state_cb.Text = "";
            end_state_cb.Text = "";
            associated_event_cb.Text = "";
            loadStateTransitionsPolicyStatementList(newStateTransition);

            new_ent_name_tb.Visibility = System.Windows.Visibility.Hidden;
            new_ent_Name_l.Visibility = System.Windows.Visibility.Hidden;
            apply_new_event_b.Visibility = System.Windows.Visibility.Hidden;
            new_ent_desc_tb.Visibility = System.Windows.Visibility.Hidden;
            new_event_ppties_gb.Visibility = System.Windows.Visibility.Hidden;
            desc_l.Visibility = System.Windows.Visibility.Hidden;
            update_event_b.Visibility = System.Windows.Visibility.Hidden;
            delete_event_b.Visibility = System.Windows.Visibility.Hidden;
            define_state_b.Visibility = System.Windows.Visibility.Hidden;
            delete_state_b.Visibility = System.Windows.Visibility.Hidden;
            update_state_b.Visibility = System.Windows.Visibility.Hidden;
            operational_atts_gb.Visibility = System.Windows.Visibility.Hidden;
            state_action_apply_b.Visibility = System.Windows.Visibility.Hidden;
            state_action_update_b.Visibility = System.Windows.Visibility.Hidden;
            state_action_delete_b.Visibility = System.Windows.Visibility.Hidden;
            transitionPolicies_gb.Visibility = System.Windows.Visibility.Hidden;
            update_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            apply_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            start_state_l.Visibility = System.Windows.Visibility.Hidden;
            start_state_cb.Visibility = System.Windows.Visibility.Hidden;
            ass_event_l.Visibility = System.Windows.Visibility.Hidden;
            associated_event_cb.Visibility = System.Windows.Visibility.Hidden;
            end_state_l.Visibility = System.Windows.Visibility.Hidden;
            end_state_cb.Visibility = System.Windows.Visibility.Hidden;
            delete_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            isCallableState_cb.Visibility = System.Windows.Visibility.Hidden;
            isCallableTransition_cb.Visibility = System.Windows.Visibility.Hidden;

            genStateMachineGraph();
        }

        private void update_new_state_transition_b_Click(object sender, RoutedEventArgs e)
        {
            string transitionName = new_ent_name_tb.Text;
            transitionName = transitionName.Trim();
            transitionName = transitionName.TrimEnd('\n');
            transitionName = transitionName.TrimEnd('\r');

            string startState = start_state_cb.Text;
            string endState = end_state_cb.Text;
            string associatedEvent = associated_event_cb.Text;
            
            if (transitionName.Count() == 0)
            {
                MessageBoxResult result = MessageBox.Show(this, "Transition name field is empty",
                            "error", MessageBoxButton.OK,
                            MessageBoxImage.Information);                
                return;
            }
            else if (startState.Count() == 0)
            {
                MessageBoxResult result = MessageBox.Show(this, "start state field is empty",
                            "error", MessageBoxButton.OK,
                            MessageBoxImage.Information);
                return;
            }
            else if (endState.Count() == 0)
            {
                MessageBoxResult result = MessageBox.Show(this, "end state field is empty",
                            "error", MessageBoxButton.OK,
                            MessageBoxImage.Information);
                return;
            }
            else if (associatedEvent.Count() == 0)
            {
                MessageBoxResult result = MessageBox.Show(this, "associated event field is empty",
                            "error", MessageBoxButton.OK,
                            MessageBoxImage.Information);
                return;
            }

            ////if (existingStateTransition(transitionName, startState, endState, associatedEvent))
            //if (existingStateTransition(transitionName))
            //{
            //    MessageBoxResult result = MessageBox.Show(this, transitionName + " already exist",
            //                                "error", MessageBoxButton.OK,
            //                                MessageBoxImage.Information);
            //    return;
            //}
            
            if (newStateTransition == null)
            {
                return;
            }
            string trans_content_old = newStateTransition.transitionName + "(" + newStateTransition.startState +
                "," + newStateTransition.endState + "," + newStateTransition.associatedEevent + ")";
            string trans_tag_old = newStateTransition.transitionName + "," + newStateTransition.machineName + "," + newStateTransition.startState +
                    "," + newStateTransition.endState + "," + newStateTransition.associatedEevent;

            foreach (TreeViewItem item in transitions.Items)
            {
                string tagx = (string)item.Tag;
                if (tagx.Equals(trans_tag_old))
                {
                    transitions.Items.Remove(item);
                    break;
                }
            }

            newStateTransition.transitionName = transitionName;
            newStateTransition.startState = startState;
            newStateTransition.endState = endState;
            newStateTransition.associatedEevent = associatedEvent;

            if (isCallableTransition_cb.IsChecked == true)
            {
                newStateTransition.isCallable = true;
            }
            else
            {
                newStateTransition.isCallable = false;
            }

            //MisUseAnObjectsDB.updateStateTransitionDB(newStateTransition, MainWindow.clusterName);
            machine_.updateStateTransition(newStateTransition);
            MisUseAnObjectsDB.addStateMachineDB(machine_, MainWindow.clusterName);

            string trans_tag = newStateTransition.transitionName + "," + newStateTransition.machineName + "," + newStateTransition.startState +
                    "," + newStateTransition.endState + "," + newStateTransition.associatedEevent;
            string trans_content = newStateTransition.transitionName + "(" + newStateTransition.startState +
                "," + newStateTransition.endState + "," + newStateTransition.associatedEevent + ")";
            if (!transitions.Items.Contains(trans_content))
            {
                TreeViewItem item = new TreeViewItem();
                item.Header = trans_content;
                item.Tag = trans_tag;
                item.AddHandler(TreeViewItem.SelectedEvent, new RoutedEventHandler(transition_TreeViewItem_Selected));

                //if (newStateTransition.isMitigationPoint == true)
                //{
                //    item.Background = Brushes.LightYellow;
                //}
                if (newStateTransition.isMisusePoint == true)
                {
                    item.Background = Brushes.OrangeRed;
                }

                MitigationReferences m_ref_s = MisUseAnObjectsDB.loadTransitionMitigationReferencesDB(newStateTransition.transitionName, machineName_, MainWindow.clusterName);

                if (m_ref_s.isEmpty == false)
                {
                    item.Background = Brushes.Green;
                }

                ContextMenu cm_trans = new System.Windows.Controls.ContextMenu();
                cm_trans.Height = 60;
                cm_trans.Width = 150;

                //MenuItem cm_mp_trans = new MenuItem();
                //cm_mp_trans.Header = "mitigation point";
                //cm_mp_trans.Tag = trans_tag;
                //if (newStateTransition.isMitigationPoint == true)
                //{
                //    cm_mp_trans.IsChecked = true;
                //}
                //cm_mp_trans.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(mitigation_point_transition_clicked));
                //cm_mp_trans.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(mitigation_point_transition_clicked));
                //cm_mp_trans.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                //cm_mp_trans.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                //cm_mp_trans.FontSize = 10;
                //cm_mp_trans.Background = Brushes.LightYellow;
                //cm_mp_trans.IsCheckable = true;

                MenuItem cm_mu_trans = new MenuItem();
                cm_mu_trans.Header = "misuse point";
                cm_mu_trans.Tag = trans_tag;
                if (newStateTransition.isMisusePoint == true)
                {
                    cm_mu_trans.IsChecked = true;
                }
                cm_mu_trans.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(misuse_point_transition_clicked));
                cm_mu_trans.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(misuse_point_transition_clicked));
                cm_mu_trans.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                cm_mu_trans.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                cm_mu_trans.FontSize = 10;
                //cm_mu_trans.Background = Brushes.OrangeRed;
                cm_mu_trans.IsCheckable = true;

                MenuItem cm_m_mr = new MenuItem();
                cm_m_mr.Header = "Mitigation references";
                cm_m_mr.Tag = trans_tag;

                if (newStateTransition.isMisusePoint == false)
                {
                    cm_m_mr.IsEnabled = false;
                }
                if (m_ref_s.isEmpty == false)
                {
                    cm_m_mr.IsChecked = true;
                }
                cm_m_mr.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(mitigation_references_transition_clicked));
                cm_m_mr.AddHandler(MenuItem.UncheckedEvent, new RoutedEventHandler(mitigation_references_transition_clicked));
                cm_m_mr.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                cm_m_mr.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                cm_m_mr.FontSize = 10;
                //cm_m_act.Background = Brushes.OrangeRed;
                cm_m_mr.IsCheckable = true;

                //cm_trans.Items.Add(cm_mp_trans);
                cm_trans.Items.Add(cm_mu_trans);
                cm_trans.Items.Add(cm_m_mr);

                item.ContextMenu = cm_trans;
                transitions.Items.Add(item);
            }

            newStateTransition = new Transition();
            newStateTransition.machineName = machineName_;
            newStateTransition.clusterName = MainWindow.clusterName;
            new_ent_name_tb.Text = "";
            start_state_cb.Text = "";
            end_state_cb.Text = "";
            associated_event_cb.Text = "";
            loadStateTransitionsPolicyStatementList(newStateTransition);  

            new_ent_name_tb.Visibility = System.Windows.Visibility.Hidden;
            new_ent_Name_l.Visibility = System.Windows.Visibility.Hidden;
            apply_new_event_b.Visibility = System.Windows.Visibility.Hidden;
            new_ent_desc_tb.Visibility = System.Windows.Visibility.Hidden;
            new_event_ppties_gb.Visibility = System.Windows.Visibility.Hidden;
            desc_l.Visibility = System.Windows.Visibility.Hidden;
            update_event_b.Visibility = System.Windows.Visibility.Hidden;
            delete_event_b.Visibility = System.Windows.Visibility.Hidden;
            define_state_b.Visibility = System.Windows.Visibility.Hidden;
            delete_state_b.Visibility = System.Windows.Visibility.Hidden;
            update_state_b.Visibility = System.Windows.Visibility.Hidden;
            operational_atts_gb.Visibility = System.Windows.Visibility.Hidden;
            state_action_apply_b.Visibility = System.Windows.Visibility.Hidden;
            state_action_update_b.Visibility = System.Windows.Visibility.Hidden;
            state_action_delete_b.Visibility = System.Windows.Visibility.Hidden;
            transitionPolicies_gb.Visibility = System.Windows.Visibility.Hidden;
            update_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            apply_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            start_state_l.Visibility = System.Windows.Visibility.Hidden;
            start_state_cb.Visibility = System.Windows.Visibility.Hidden;
            ass_event_l.Visibility = System.Windows.Visibility.Hidden;
            associated_event_cb.Visibility = System.Windows.Visibility.Hidden;
            end_state_l.Visibility = System.Windows.Visibility.Hidden;
            end_state_cb.Visibility = System.Windows.Visibility.Hidden;
            delete_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
            isCallableState_cb.Visibility = System.Windows.Visibility.Hidden;
            isCallableTransition_cb.Visibility = System.Windows.Visibility.Hidden;
            
            genStateMachineGraph();
        }

        private void delete_state_transition_b_Click(object sender, RoutedEventArgs e)
        {
            string transitionName = new_ent_name_tb.Text;
            transitionName = transitionName.Trim();
            transitionName = transitionName.TrimEnd('\n');
            transitionName = transitionName.TrimEnd('\r');

            string startState = start_state_cb.Text;
            string endState = end_state_cb.Text;
            string associatedEvent = associated_event_cb.Text;

            if (transitionName.Count() == 0)
            {
                MessageBoxResult result = MessageBox.Show(this, "Transition name field is empty",
                            "error", MessageBoxButton.OK,
                            MessageBoxImage.Information);
                return;
            }
            else if (startState.Count() == 0)
            {
                MessageBoxResult result = MessageBox.Show(this, "start state field is empty",
                            "error", MessageBoxButton.OK,
                            MessageBoxImage.Information);
                return;
            }
            else if (endState.Count() == 0)
            {
                MessageBoxResult result = MessageBox.Show(this, "end state field is empty",
                            "error", MessageBoxButton.OK,
                            MessageBoxImage.Information);
                return;
            }
            else if (associatedEvent.Count() == 0)
            {
                MessageBoxResult result = MessageBox.Show(this, "associated event field is empty",
                            "error", MessageBoxButton.OK,
                            MessageBoxImage.Information);
                return;
            }

            if (newStateTransition == null)
            {
                newStateTransition = new Transition();
                newStateTransition.machineName = machineName_;
                newStateTransition.clusterName = MainWindow.clusterName;
            }
            newStateTransition.transitionName = transitionName;
            newStateTransition.startState = startState;
            newStateTransition.endState = endState;
            newStateTransition.associatedEevent = associatedEvent;

            MessageBoxResult result1 = MessageBox.Show(this, transitionName + " transition will be deleted permanently!",
                            "Confirm", MessageBoxButton.YesNo,
                            MessageBoxImage.Information);

            if (result1 == MessageBoxResult.No)
            {
                return;
            }
            else
            {
                MisUseAnObjectsDB.deleteStateTransitionDBTransStateEvent(newStateTransition, MainWindow.clusterName);
                if (machine_ != null)
                {
                    machine_.removeStateTransition(newStateTransition.transitionName);
                    MisUseAnObjectsDB.addStateMachineDB(machine_, MainWindow.clusterName);
                }


                allExistingStateTransitions = MisUseAnObjectsDB.loadAllStateTransitions(machineName_, MainWindow.clusterName);
                newStateTransition = new Transition();
                newStateTransition.machineName = machineName_;
                newStateTransition.clusterName = MainWindow.clusterName;

                new_ent_name_tb.Text = "";
                new_ent_name_tb.IsReadOnly = false;
                start_state_cb.Text = "";
                start_state_cb.IsEnabled = true;
                end_state_cb.Text = "";
                end_state_cb.IsEnabled = true;
                associated_event_cb.Text = "";
                associated_event_cb.IsEnabled = true;
                loadStateTransitionsPolicyStatementList(newStateTransition);

                new_ent_name_tb.Visibility = System.Windows.Visibility.Hidden;
                new_ent_Name_l.Visibility = System.Windows.Visibility.Hidden;
                apply_new_event_b.Visibility = System.Windows.Visibility.Hidden;
                new_ent_desc_tb.Visibility = System.Windows.Visibility.Hidden;
                new_event_ppties_gb.Visibility = System.Windows.Visibility.Hidden;
                desc_l.Visibility = System.Windows.Visibility.Hidden;
                update_event_b.Visibility = System.Windows.Visibility.Hidden;
                delete_event_b.Visibility = System.Windows.Visibility.Hidden;
                delete_state_b.Visibility = System.Windows.Visibility.Hidden;
                update_state_b.Visibility = System.Windows.Visibility.Hidden;
                define_state_b.Visibility = System.Windows.Visibility.Hidden;
                operational_atts_gb.Visibility = System.Windows.Visibility.Hidden;
                state_action_apply_b.Visibility = System.Windows.Visibility.Hidden;
                state_action_update_b.Visibility = System.Windows.Visibility.Hidden;
                state_action_delete_b.Visibility = System.Windows.Visibility.Hidden;
                transitionPolicies_gb.Visibility = System.Windows.Visibility.Hidden;
                update_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
                apply_new_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
                start_state_l.Visibility = System.Windows.Visibility.Hidden;
                start_state_cb.Visibility = System.Windows.Visibility.Hidden;
                ass_event_l.Visibility = System.Windows.Visibility.Hidden;
                associated_event_cb.Visibility = System.Windows.Visibility.Hidden;
                end_state_l.Visibility = System.Windows.Visibility.Hidden;
                end_state_cb.Visibility = System.Windows.Visibility.Hidden;
                delete_state_transition_b.Visibility = System.Windows.Visibility.Hidden;
                isCallableState_cb.Visibility = System.Windows.Visibility.Hidden;
                isCallableTransition_cb.Visibility = System.Windows.Visibility.Hidden;

                foreach (TreeViewItem item in transitions.Items)
                {
                    string tag_id = (string)item.Tag;
                    if (!tag_id.Equals("new"))
                    {
                        string[] tag_comps = tag_id.Split(',');
                        string transitionName_t = tag_comps[0];
                        string machineName_t = tag_comps[1];
                        string startState_t = tag_comps[2];
                        string endState_t = tag_comps[3];
                        string associatedEvent_t = tag_comps[4];

                        if (transitionName_t.Equals(transitionName)
                            && machineName_t.Equals(machineName_)
                            && startState_t.Equals(startState)
                            && endState_t.Equals(endState)
                            && associatedEvent_t.Equals(associatedEvent))
                        {
                            transitions.Items.Remove(item);
                            break;
                        }
                    }                    
                }
            }

            genStateMachineGraph();
        }

        string genNodeID(Graph graph)
        {
            int id = 0;
            foreach (DictionaryEntry entry in graph.NodeMap)
            {
                string key = (string)entry.Key;
                string id_s = ""+id;
                if (key.Equals(id_s))
                {
                    id = id + 1;
                }
            }
            return "" + id;

        }
        void genStateMachineGraph()
        {
            InitializeComponent();

            //Serialize(fsm);
            glee_fsm_graph = CreateFSMGraph();

            glee_fsm_graph.Attr.LayerDirection = LayerDirection.None;
            glee_fsm_graph.Attr.AspectRatio = 1.7;

            Hashtable nodes = glee_fsm_graph.NodeMap;
            ICollection<Edge> edges = glee_fsm_graph.Edges;
            
            //display every other node with in or out nodes
            foreach (Transition t in machine_.transitions)
            {
                if (t.isMisusePoint == true)
                {
                    MitigationReferences m_ref = MisUseAnObjectsDB.
                    loadTransitionMitigationReferencesDB(t.transitionName, machineName_, MainWindow.clusterName);

                    if (m_ref.isEmpty == true)
                    {
                        int index = 0;
                        foreach (Edge edge in edges)
                        {
                            string[] l_s = edge.LabelText.Split('(');
                            string t_label_n = l_s[0];
                            if (t_label_n.Equals(t.transitionName))
                            {
                                Edge e_n = glee_fsm_graph.Edges.ElementAt(index);
                                if (e_n != null)
                                {
                                    e_n.Attr.Color = Microsoft.Msagl.Drawing.Color.OrangeRed;
                                }
                            }
                            index = index + 1;
                        }
                    }
                    else
                    {
                        string t_sourceNode_key = null;
                        string t_endNode_key = null;
                        string t_endNode_final_key = null;

                        //remove misuse edge
                        foreach (DictionaryEntry entry in nodes)
                        {
                            Node n = (Node)entry.Value;
                            if (n.LabelText.Equals(t.startState))
                            {
                                t_sourceNode_key = (string)entry.Key;
                            }
                            else if (n.LabelText.Equals(t.endState))
                            {
                                t_endNode_key = (string)entry.Key;
                                t_endNode_final_key = (string)entry.Key;
                            }
                            //if(t_sourceNode_key != null && t_endNode_key != null)
                            //{
                            //    break;
                            //}
                        }

                        if (t_sourceNode_key != null && t_endNode_key != null)
                        {
                            Edge t_edge = null;
                            foreach (Edge edge in edges)
                            {
                                if (edge.Source == t_sourceNode_key && edge.Target == t_endNode_key)
                                {
                                    t_edge = edge;
                                    break;
                                }
                            }
                            glee_fsm_graph.Edges.Remove(t_edge);

                            //add mitigation edges (mitigation transitions)                            
                            var mitigation_trans = new Dictionary<Transition, int>();
                            foreach (Transition trans in m_ref.transitions)
                            {
                                mitigation_trans.Add(trans, trans.mitigationSeqRefIndex);
                            }

                            var ordered_mitigation_trans = from k in mitigation_trans.Keys
                                                           orderby mitigation_trans[k] ascending
                                                           select k;

                            Edge t_mmu_edge = null;
                            string desc_t_mmu = null;
                            int mit_no = 1;
                            string t_mr_sourceNode_key = null;
                            string t_mr_endNode_key = null;
                            
                            if (m_ref.transitions.Count() == 0)
                            {
                                t_mr_endNode_key = t_sourceNode_key;
                            }

                            for (int i = 0; i < ordered_mitigation_trans.Count(); i++)
                            {
                                Transition t_mr = ordered_mitigation_trans.ElementAt(i);                              

                                foreach (DictionaryEntry entry in nodes)
                                {
                                    Node n = (Node)entry.Value;
                                    if (n.LabelText.Equals(t_mr.startState))
                                    {
                                        t_mr_sourceNode_key = (string)entry.Key;
                                    }
                                    else if (n.LabelText.Equals(t_mr.endState))
                                    {
                                        t_mr_endNode_key = (string)entry.Key;
                                    }
                                    //if (t_mr_sourceNode_key != null && t_mr_endNode_key != null)
                                    //{
                                    //    break;
                                    //}
                                }

                                if (t_mr_sourceNode_key == null)
                                {
                                    t_mr_sourceNode_key = genNodeID(glee_fsm_graph);
                                    glee_fsm_graph.NodeMap.Add(t_mr_sourceNode_key, t_mr.startState);
                                }
                                if (t_mr_endNode_key == null)
                                {
                                    t_mr_endNode_key = genNodeID(glee_fsm_graph);
                                    glee_fsm_graph.NodeMap.Add(t_mr_endNode_key, t_mr.endState);
                                }

                                string desc_t_mmu_mit = t.transitionName + "[MITIGATED][" + mit_no+ "]";
                                mit_no = mit_no + 1;
                                Edge t_mmu_mit_edge = null;
                                t_mmu_mit_edge = new Edge(t_sourceNode_key, desc_t_mmu_mit, t_mr_sourceNode_key);
                                t_mmu_mit_edge.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                glee_fsm_graph.Edges.Add(t_mmu_mit_edge);

                                string desc_t_mr = t_mr.transitionName + "(" + t_mr.associatedEevent + ")["+mit_no+"]";
                                mit_no = mit_no + 1;
                                Edge t_mr_edge = null;
                                t_mr_edge = new Edge(t_mr_sourceNode_key, desc_t_mr, t_mr_endNode_key);
                                t_mr_edge.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                glee_fsm_graph.Edges.Add(t_mr_edge);

                                if (ordered_mitigation_trans.Count() > (i + 1))
                                {
                                    Transition trans_next = ordered_mitigation_trans.ElementAt(i+1);

                                    foreach (DictionaryEntry entry in nodes)
                                    {
                                        Node n = (Node)entry.Value;

                                        if (n.LabelText.Equals(t_mr.startState))
                                        {
                                            t_mr_sourceNode_key = (string)entry.Key;
                                        }
                                        else if (n.LabelText.Equals(t_mr.endState))
                                        {
                                            t_mr_endNode_key = (string)entry.Key;
                                        }

                                        if (n.Equals(trans_next.startState))
                                        {
                                            t_endNode_key = (string)entry.Key;
                                        }
                                    }
                                    t_sourceNode_key = t_mr_endNode_key;
                                }
                                else
                                {
                                    desc_t_mmu = t.transitionName + "(" + t.associatedEevent + ")["+mit_no+"]";
                                   
                                }                               

                            }

                            //add mitigation nodes (mitigation states)
                            var mitigation_states = new Dictionary<State, int>();
                            foreach(State state in m_ref.states)
                            {
                                mitigation_states.Add(state, state.mitigationSeqRefIndex);
                            }

                            var ordered_mitigation_states = from k in mitigation_states.Keys
                                                            orderby mitigation_states[k] ascending
                                                            select k;

                            for (int i = 0; i < ordered_mitigation_states.Count(); i++)
                            {
                                State s_mr = ordered_mitigation_states.ElementAt(i);

                                string s_mr_node_key = null;
                                foreach (DictionaryEntry entry in nodes)
                                {
                                    Node n = (Node)entry.Value;
                                    if (n.LabelText.Equals(s_mr.name))
                                    {
                                        s_mr_node_key = (string)entry.Key;
                                        break;
                                    }
                                }
                                Node s_nr_node = null;
                                if (s_mr_node_key != null)
                                {
                                    s_nr_node = glee_fsm_graph.FindNode(s_mr_node_key);
                                    s_nr_node.Attr.FillColor = Microsoft.Msagl.Drawing.Color.LightGreen;
                                    Edge edge_s_m = new Edge(t_mr_endNode_key, "[M:"+s_mr.name+"]", s_mr_node_key);
                                    edge_s_m.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                    glee_fsm_graph.Edges.Add(edge_s_m);
                                    
                                    t_mr_endNode_key = s_mr_node_key;
                                }
                            }

                            desc_t_mmu = "M:"+t.transitionName + "(" + t.associatedEevent + ")[" + mit_no + "]";
                            t_mmu_edge = new Edge(t_mr_endNode_key, desc_t_mmu, t_endNode_final_key);                                 
                            t_mmu_edge.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                            glee_fsm_graph.Edges.Add(t_mmu_edge);


                            //add mitigation actions

                            for (int i = 0; i < m_ref.actions.Count(); i++)
                            {
                                PMisuseAn.behaviour.model.Action s_a_mr = m_ref.actions.ElementAt(i);

                                String s_mr_name = s_a_mr.stateName;
                                string s_mr_node_key = null;
                                foreach (DictionaryEntry entry in nodes)
                                {
                                    Node n = (Node)entry.Value;
                                    if (n.LabelText.Equals(s_mr_name))
                                    {
                                        s_mr_node_key = (string)entry.Key;
                                        break;
                                    }
                                }
                                Node s_nr_node = null;
                                if (s_mr_node_key != null)
                                {
                                    s_nr_node = glee_fsm_graph.FindNode(s_mr_node_key);
                                    s_nr_node.Attr.FillColor = Microsoft.Msagl.Drawing.Color.LightGreen;
                                    Edge edge_s_m = new Edge(t_mr_endNode_key, "ACT-[M:" + s_mr_name + "]ACT", s_mr_node_key);
                                    edge_s_m.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                    glee_fsm_graph.Edges.Add(edge_s_m);

                                    t_mr_endNode_key = s_mr_node_key;
                                }
                            }
                        }                        
                    }                    
                }
            }


            foreach (State s in machine_.states)
            {
                if (s.isMisusePoint == true)
                {
                    MitigationReferences m_ref = MisUseAnObjectsDB.
                                        loadStateMitigationReferencesDB(s.name, machineName_, MainWindow.clusterName);
                    Node s_node = null;
                    string s_node_key = null;
                    
                    string t_endNode_final_key = null;

                    foreach (DictionaryEntry entry in nodes)
                    {
                        Node n = (Node)entry.Value;
                        if (n.LabelText.Equals(s.name))
                        {
                            s_node_key = (string)entry.Key;
                            t_endNode_final_key = s_node_key;
                            break;
                        }
                    }
                    s_node = glee_fsm_graph.FindNode(s_node_key);

                    if (s_node != null && m_ref.isEmpty == true)
                    {
                        s_node.Attr.FillColor = Microsoft.Msagl.Drawing.Color.OrangeRed; 
                    }

                    else if (s_node != null && m_ref.isEmpty == false)
                    {
                        //add mitigation edges (mitigation transitions)                            
                        var mitigation_trans = new Dictionary<Transition, int>();
                        foreach (Transition trans in m_ref.transitions)
                        {
                            mitigation_trans.Add(trans, trans.mitigationSeqRefIndex);
                        }

                        var ordered_mitigation_trans = from k in mitigation_trans.Keys
                                                       orderby mitigation_trans[k] ascending
                                                       select k;                       
                        
                        int mit_no = 1;
                        string t_mr_sourceNode_key = null;
                        string t_mr_endNode_key = null;

                        IEnumerable<Edge> _s_in_edges = s_node.InEdges;
                        IEnumerable<Edge> _s_self_edges = s_node.SelfEdges;

                        if (_s_in_edges.Count() == 0 && _s_self_edges.Count() == 0)
                        {
                            string last_t_mr_endNode_key = null;
                            Edge t_mmu_edge = null;

                            for (int i = 0; i < ordered_mitigation_trans.Count(); i++)
                            {
                                Transition t_mr = ordered_mitigation_trans.ElementAt(i);
                            
                                foreach (DictionaryEntry entry in nodes)
                                {
                                    Node n = (Node)entry.Value;

                                    if (n.LabelText.Equals(t_mr.startState))
                                    {
                                        t_mr_sourceNode_key = (string)entry.Key;
                                    }
                                    else if (n.LabelText.Equals(t_mr.endState))
                                    {
                                        t_mr_endNode_key = (string)entry.Key;
                                    }
                                    //if (t_mr_sourceNode_key != null && t_mr_endNode_key != null)
                                    //{
                                    //    break;
                                    //}
                                }
                                if (t_mr_sourceNode_key == null)
                                {
                                    t_mr_sourceNode_key = genNodeID(glee_fsm_graph);
                                    glee_fsm_graph.NodeMap.Add(t_mr_sourceNode_key, t_mr.startState);
                                }
                                if (t_mr_endNode_key == null)
                                {
                                    t_mr_endNode_key = genNodeID(glee_fsm_graph);
                                    glee_fsm_graph.NodeMap.Add(t_mr_endNode_key, t_mr.endState);
                                }
                                if(last_t_mr_endNode_key != null)
                                {
                                    string last_desc_t_mmu_mit = "T[MIT-LINK]";
                                    Edge last_t_mmu_mit_edge = null;
                                    last_t_mmu_mit_edge = new Edge(last_t_mr_endNode_key, last_desc_t_mmu_mit, t_mr_sourceNode_key);
                                    last_t_mmu_mit_edge.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                    glee_fsm_graph.Edges.Add(last_t_mmu_mit_edge);
                                }
                                string desc_t_mmu_mit = t_mr.transitionName + "[MITIGATED][" + mit_no + "]";
                                mit_no = mit_no + 1;
                                Edge t_mmu_mit_edge = null;
                                t_mmu_mit_edge = new Edge(t_mr_sourceNode_key, desc_t_mmu_mit, t_mr_endNode_key);
                                t_mmu_mit_edge.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                glee_fsm_graph.Edges.Add(t_mmu_mit_edge);

                                last_t_mr_endNode_key = t_mr_endNode_key;
                            }

                            if (m_ref.states.Count() == 0 && m_ref.actions.Count() ==0)
                            {
                                string final_desc_t_mmu_mit = "T[MIT-LINK-F]";
                                mit_no = mit_no + 1;
                                Edge final_t_mmu_mit_edge = null;
                                final_t_mmu_mit_edge = new Edge(last_t_mr_endNode_key, final_desc_t_mmu_mit, t_endNode_final_key);
                                final_t_mmu_mit_edge.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                glee_fsm_graph.Edges.Add(final_t_mmu_mit_edge);
                            }
                            else
                            {

                            }                                                               
               

                            //add mitigation nodes (mitigation states)
                            var mitigation_states = new Dictionary<State, int>();
                            foreach (State state in m_ref.states)
                            {
                                mitigation_states.Add(state, state.mitigationSeqRefIndex);
                            }

                            var ordered_mitigation_states = from k in mitigation_states.Keys
                                                            orderby mitigation_states[k] ascending
                                                            select k;

                            for (int i = 0; i < ordered_mitigation_states.Count(); i++)
                            {
                                State s_mr = ordered_mitigation_states.ElementAt(i);

                                string s_mr_node_key = null;
                                foreach (DictionaryEntry entry in nodes)
                                {
                                    Node n = (Node)entry.Value;
                                    if (n.LabelText.Equals(s_mr.name))
                                    {
                                        s_mr_node_key = (string)entry.Key;
                                        break;
                                    }
                                }
                                Node s_nr_node = null;
                                if (s_mr_node_key != null)
                                {
                                    s_nr_node = glee_fsm_graph.FindNode(s_mr_node_key);
                                    s_nr_node.Attr.FillColor = Microsoft.Msagl.Drawing.Color.LightGreen;
                                   // Edge edge_s_m = new Edge(t_mr_endNode_key, "[M:" + s_mr.name + "]", s_mr_node_key);

                                    Edge edge_s_m = null;
                                    if (m_ref.states.Count() > 0 && t_mr_endNode_key != null)
                                    {
                                        edge_s_m = new Edge(t_mr_endNode_key, "[M:" + s_mr.name + "]", s_mr_node_key);
                                        edge_s_m.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                        glee_fsm_graph.Edges.Add(edge_s_m);
                                    }
                                    else if (t_mr_endNode_key != null)
                                    {
                                        edge_s_m = new Edge(s_mr_node_key, "[M:" + s_mr.name + "]", t_endNode_final_key);
                                        edge_s_m.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                        glee_fsm_graph.Edges.Add(edge_s_m);
                                    }

                                    //edge_s_m.Attr.Color = Microsoft.Glee.Drawing.Color.Green;
                                    //glee_fsm_graph.Edges.Add(edge_s_m);

                                    t_mr_endNode_key = s_mr_node_key;
                                }
                            }

                            if (m_ref.states.Count() > 0 && m_ref.actions.Count() ==0)
                            {
                                string desc_t_mmu = "M:[T-S]";
                                t_mmu_edge = new Edge(t_mr_endNode_key, desc_t_mmu, t_endNode_final_key);
                                t_mmu_edge.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                glee_fsm_graph.Edges.Add(t_mmu_edge);
                            }


                            //add mitigation actions

                            for (int i = 0; i < m_ref.actions.Count(); i++)
                            {
                                PMisuseAn.behaviour.model.Action s_a_mr = m_ref.actions.ElementAt(i);

                                String s_mr_name = s_a_mr.stateName;
                                string s_mr_node_key = null;
                                foreach (DictionaryEntry entry in nodes)
                                {
                                    Node n = (Node)entry.Value;
                                    if (n.LabelText.Equals(s_mr_name))
                                    {
                                        s_mr_node_key = (string)entry.Key;
                                        break;
                                    }
                                }
                                Node s_nr_node = null;
                                if (s_mr_node_key != null)
                                {
                                    s_nr_node = glee_fsm_graph.FindNode(s_mr_node_key);
                                    s_nr_node.Attr.FillColor = Microsoft.Msagl.Drawing.Color.LightGreen;
                                    Edge edge_s_m = new Edge(t_mr_endNode_key, "ACT-[M:" + s_mr_name + "]ACT", s_mr_node_key);
                                    edge_s_m.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                    glee_fsm_graph.Edges.Add(edge_s_m);

                                    t_mr_endNode_key = s_mr_node_key;
                                }
                            }

                            if (m_ref.states.Count() > 0 && m_ref.actions.Count > 0)
                            {
                                string desc_t_mmu = "ACT-M:[T-S]ACT";
                                t_mmu_edge = new Edge(t_mr_endNode_key, desc_t_mmu, t_endNode_final_key);
                                t_mmu_edge.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                glee_fsm_graph.Edges.Add(t_mmu_edge);
                            }
                        }
                        else
                        {
                            foreach (Edge s_in_edge in _s_in_edges)
                            {
                                //remove edge from _s_node
                                glee_fsm_graph.Edges.Remove(s_in_edge);

                                //get s_in_edge_keys and recreate new edge link to mitigation ref
                                string s_in_edge_source_key = s_in_edge.SourceNode.Id;
                                string s_in_edge_target_key = s_in_edge.TargetNode.Id;
                                string s_in_edge_label = s_in_edge.LabelText;

                                string last_t_mr_endNode_key = null;
                                Edge t_mmu_edge = null;
                                                               
                                for (int i = 0; i < ordered_mitigation_trans.Count(); i++)
                                {
                                    Transition t_mr = ordered_mitigation_trans.ElementAt(i);
                            
                                    foreach (DictionaryEntry entry in nodes)
                                    {
                                        Node n = (Node)entry.Value;

                                        if (n.LabelText.Equals(t_mr.startState))
                                        {
                                            t_mr_sourceNode_key = (string)entry.Key;
                                        }
                                        else if (n.LabelText.Equals(t_mr.endState))
                                        {
                                            t_mr_endNode_key = (string)entry.Key;
                                        }
                                        //if (t_mr_sourceNode_key != null && t_mr_endNode_key != null)
                                        //{
                                        //    break;
                                        //}
                                    }
                                    if (t_mr_sourceNode_key == null)
                                    {
                                        t_mr_sourceNode_key = genNodeID(glee_fsm_graph);
                                        glee_fsm_graph.NodeMap.Add(t_mr_sourceNode_key, t_mr.startState);
                                    }
                                    if (t_mr_endNode_key == null)
                                    {
                                        t_mr_endNode_key = genNodeID(glee_fsm_graph);
                                        glee_fsm_graph.NodeMap.Add(t_mr_endNode_key, t_mr.endState);
                                    }
                                    if(last_t_mr_endNode_key != null)
                                    {
                                        string last_desc_t_mmu_mit = "T[MIT-LINK]";
                                        Edge last_t_mmu_mit_edge = null;
                                        last_t_mmu_mit_edge = new Edge(last_t_mr_endNode_key, last_desc_t_mmu_mit, t_mr_sourceNode_key);
                                        last_t_mmu_mit_edge.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                        glee_fsm_graph.Edges.Add(last_t_mmu_mit_edge);
                                    }
                                    else
                                    {
                                        string last_desc_t_mmu_mit = "T[MIT-LINK]";
                                        Edge last_t_mmu_mit_edge = null;
                                        last_t_mmu_mit_edge = new Edge(s_in_edge_source_key, last_desc_t_mmu_mit, t_mr_sourceNode_key);
                                        last_t_mmu_mit_edge.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                        glee_fsm_graph.Edges.Add(last_t_mmu_mit_edge); 
                                    }
                                    string desc_t_mmu_mit = t_mr.transitionName + "[MITIGATED][" + mit_no + "]";
                                    mit_no = mit_no + 1;
                                    Edge t_mmu_mit_edge = null;
                                    t_mmu_mit_edge = new Edge(t_mr_sourceNode_key, desc_t_mmu_mit, t_mr_endNode_key);
                                    t_mmu_mit_edge.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                    glee_fsm_graph.Edges.Add(t_mmu_mit_edge);

                                    last_t_mr_endNode_key = t_mr_endNode_key;    

                                }

                                if (m_ref.states.Count() == 0 && m_ref.actions.Count()==0)
                                {
                                    string final_desc_t_mmu_mit = "M:"+s_in_edge_label+"]";
                                    mit_no = mit_no + 1;
                                    Edge final_t_mmu_mit_edge = null;
                                    final_t_mmu_mit_edge = new Edge(last_t_mr_endNode_key, final_desc_t_mmu_mit, s_in_edge_target_key);
                                    final_t_mmu_mit_edge.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                    glee_fsm_graph.Edges.Add(final_t_mmu_mit_edge);                               
                                }
                                
                                //add mitigation nodes (mitigation states)
                                var mitigation_states = new Dictionary<State, int>();
                                foreach (State state in m_ref.states)
                                {
                                    mitigation_states.Add(state, state.mitigationSeqRefIndex);
                                }

                                var ordered_mitigation_states = from k in mitigation_states.Keys
                                                                orderby mitigation_states[k] ascending
                                                                select k;

                                for (int i = 0; i < ordered_mitigation_states.Count(); i++)
                                {
                                    State s_mr = ordered_mitigation_states.ElementAt(i);

                                    string s_mr_node_key = null;
                                    foreach (DictionaryEntry entry in nodes)
                                    {
                                        Node n = (Node)entry.Value;
                                        if (n.LabelText.Equals(s_mr.name))
                                        {
                                            s_mr_node_key = (string)entry.Key;
                                            break;
                                        }
                                    }
                                    Node s_nr_node = null;
                                    if (s_mr_node_key != null)
                                    {
                                        s_nr_node = glee_fsm_graph.FindNode(s_mr_node_key);
                                        s_nr_node.Attr.FillColor = Microsoft.Msagl.Drawing.Color.LightGreen;
                                        Edge edge_s_m = null;
                                        if (m_ref.states.Count() > 0 && t_mr_endNode_key !=null)
                                        {
                                            edge_s_m = new Edge(t_mr_endNode_key, "[M:" + s_mr.name + "]", s_mr_node_key);
                                            edge_s_m.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                            glee_fsm_graph.Edges.Add(edge_s_m);
                                        }
                                        //else if (t_mr_endNode_key != null)
                                        else
                                        {
                                            edge_s_m = new Edge(s_mr_node_key, "[M:" + s_mr.name + "]", t_endNode_final_key);
                                            edge_s_m.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                            glee_fsm_graph.Edges.Add(edge_s_m);
                                        }
                                        
                                        t_mr_endNode_key = s_mr_node_key;
                                    }
                                }

                                if (m_ref.states.Count() > 0 && m_ref.transitions.Count()>0 && m_ref.actions.Count()== 0)
                                {
                                    //string desc_t_mmu = "M:[T-S]";
                                    string final_desc_t_mmu_mit = "M:" + s_in_edge_label + "]";
                                    t_mmu_edge = new Edge(t_mr_endNode_key, final_desc_t_mmu_mit, t_endNode_final_key);
                                    t_mmu_edge.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                    glee_fsm_graph.Edges.Add(t_mmu_edge);
                                }
                                else if (m_ref.states.Count() > 0 && m_ref.transitions.Count() == 0 && m_ref.actions.Count()==0)
                                {
                                    //string desc_t_mmu = "M:[S]";
                                    string final_desc_t_mmu_mit = "M:" + s_in_edge_label + "]";
                                    //t_mmu_edge = new Edge(t_endNode_final_key, final_desc_t_mmu_mit, t_mr_endNode_key);
                                    t_mmu_edge = new Edge(s_in_edge_source_key, final_desc_t_mmu_mit, t_mr_endNode_key);                                    
                                    t_mmu_edge.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                    glee_fsm_graph.Edges.Add(t_mmu_edge);
                                }


                                //add mitigation actions

                                for (int i = 0; i < m_ref.actions.Count(); i++)
                                {
                                    PMisuseAn.behaviour.model.Action s_a_mr = m_ref.actions.ElementAt(i);

                                    String s_mr_name = s_a_mr.stateName;
                                    string s_mr_node_key = null;
                                    foreach (DictionaryEntry entry in nodes)
                                    {
                                        Node n = (Node)entry.Value;
                                        if (n.LabelText.Equals(s_mr_name))
                                        {
                                            s_mr_node_key = (string)entry.Key;
                                            break;
                                        }
                                    }
                                    Node s_nr_node = null;
                                    if (s_mr_node_key != null)
                                    {
                                        s_nr_node = glee_fsm_graph.FindNode(s_mr_node_key);
                                        s_nr_node.Attr.FillColor = Microsoft.Msagl.Drawing.Color.LightGreen;
                                        Edge edge_s_m = new Edge(t_mr_endNode_key, "ACT-[M:" + s_mr_name + "]ACT", s_mr_node_key);
                                        edge_s_m.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                        glee_fsm_graph.Edges.Add(edge_s_m);

                                        t_mr_endNode_key = s_mr_node_key;
                                    }
                                }

                                if (m_ref.states.Count() > 0 && m_ref.actions.Count > 0 && m_ref.transitions.Count>0)
                                {
                                    string desc_t_mmu = "ACT-M:[T-S]ACT";
                                    t_mmu_edge = new Edge(t_mr_endNode_key, desc_t_mmu, t_endNode_final_key);
                                    t_mmu_edge.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                    glee_fsm_graph.Edges.Add(t_mmu_edge);
                                }
                            }
                        }                       

                    }
                        
                }
           
            }

            //////////////////////////////////////////
            
            foreach (State s in machine_.states)
            {
                foreach (PMisuseAn.behaviour.model.Action action in s.actions)
                {
                    if (action.isMisusePoint == true)
                    {
                        MitigationReferences m_ref = MisUseAnObjectsDB.
                                            loadStateActionMitigationReferencesDB(action.name, s.name, machineName_, MainWindow.clusterName);
                        Node s_node = null;
                        string s_node_key = null;

                        string t_endNode_final_key = null;

                        foreach (DictionaryEntry entry in nodes)
                        {
                            Node n = (Node)entry.Value;
                            if (n.LabelText.Equals(s.name))
                            {
                                s_node_key = (string)entry.Key;
                                t_endNode_final_key = s_node_key;
                                break;
                            }
                        }
                        s_node = glee_fsm_graph.FindNode(s_node_key);

                        if (s_node != null && m_ref.isEmpty == true)
                        {
                            s_node.Attr.Color = Microsoft.Msagl.Drawing.Color.OrangeRed;
                        }

                        else if (s_node != null && m_ref.isEmpty == false)
                        {
                            //add mitigation edges (mitigation transitions)                            
                            var mitigation_trans = new Dictionary<Transition, int>();
                            foreach (Transition trans in m_ref.transitions)
                            {
                                mitigation_trans.Add(trans, trans.mitigationSeqRefIndex);
                            }

                            var ordered_mitigation_trans = from k in mitigation_trans.Keys
                                                           orderby mitigation_trans[k] ascending
                                                           select k;

                            int mit_no = 1;
                            string t_mr_sourceNode_key = null;
                            string t_mr_endNode_key = null;

                            IEnumerable<Edge> _s_in_edges = s_node.InEdges;
                            IEnumerable<Edge> _s_self_edges = s_node.SelfEdges;

                            if (_s_in_edges.Count() == 0 && _s_self_edges.Count() == 0)
                            {
                                string last_t_mr_endNode_key = null;
                                Edge t_mmu_edge = null;

                                for (int i = 0; i < ordered_mitigation_trans.Count(); i++)
                                {
                                    Transition t_mr = ordered_mitigation_trans.ElementAt(i);

                                    foreach (DictionaryEntry entry in nodes)
                                    {
                                        Node n = (Node)entry.Value;

                                        if (n.LabelText.Equals(t_mr.startState))
                                        {
                                            t_mr_sourceNode_key = (string)entry.Key;
                                        }
                                        else if (n.LabelText.Equals(t_mr.endState))
                                        {
                                            t_mr_endNode_key = (string)entry.Key;
                                        }
                                        //if (t_mr_sourceNode_key != null && t_mr_endNode_key != null)
                                        //{
                                        //    break;
                                        //}
                                    }
                                    if (t_mr_sourceNode_key == null)
                                    {
                                        t_mr_sourceNode_key = genNodeID(glee_fsm_graph);
                                        glee_fsm_graph.NodeMap.Add(t_mr_sourceNode_key, t_mr.startState);
                                    }
                                    if (t_mr_endNode_key == null)
                                    {
                                        t_mr_endNode_key = genNodeID(glee_fsm_graph);
                                        glee_fsm_graph.NodeMap.Add(t_mr_endNode_key, t_mr.endState);
                                    }
                                    if (last_t_mr_endNode_key != null)
                                    {
                                        string last_desc_t_mmu_mit = "T[ACT-MIT-LINK]";
                                        Edge last_t_mmu_mit_edge = null;
                                        last_t_mmu_mit_edge = new Edge(last_t_mr_endNode_key, last_desc_t_mmu_mit, t_mr_sourceNode_key);
                                        last_t_mmu_mit_edge.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                        glee_fsm_graph.Edges.Add(last_t_mmu_mit_edge);
                                    }
                                    string desc_t_mmu_mit = t_mr.transitionName + "[ACT-MITIGATED][" + mit_no + "]";
                                    mit_no = mit_no + 1;
                                    Edge t_mmu_mit_edge = null;
                                    t_mmu_mit_edge = new Edge(t_mr_sourceNode_key, desc_t_mmu_mit, t_mr_endNode_key);
                                    t_mmu_mit_edge.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                    glee_fsm_graph.Edges.Add(t_mmu_mit_edge);

                                    last_t_mr_endNode_key = t_mr_endNode_key;
                                }

                                if (m_ref.states.Count() == 0 && m_ref.actions.Count == 0)
                                {
                                    string final_desc_t_mmu_mit = "T[ACT-MIT-LINK-F]";
                                    mit_no = mit_no + 1;
                                    Edge final_t_mmu_mit_edge = null;
                                    final_t_mmu_mit_edge = new Edge(last_t_mr_endNode_key, final_desc_t_mmu_mit, t_endNode_final_key);
                                    final_t_mmu_mit_edge.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                    glee_fsm_graph.Edges.Add(final_t_mmu_mit_edge);
                                }
                                else
                                {

                                }


                                //add mitigation nodes (mitigation states)
                                var mitigation_states = new Dictionary<State, int>();
                                foreach (State state in m_ref.states)
                                {
                                    mitigation_states.Add(state, state.mitigationSeqRefIndex);
                                }

                                var ordered_mitigation_states = from k in mitigation_states.Keys
                                                                orderby mitigation_states[k] ascending
                                                                select k;

                                for (int i = 0; i < ordered_mitigation_states.Count(); i++)
                                {
                                    State s_mr = ordered_mitigation_states.ElementAt(i);

                                    string s_mr_node_key = null;
                                    foreach (DictionaryEntry entry in nodes)
                                    {
                                        Node n = (Node)entry.Value;
                                        if (n.LabelText.Equals(s_mr.name))
                                        {
                                            s_mr_node_key = (string)entry.Key;
                                            break;
                                        }
                                    }
                                    Node s_nr_node = null;
                                    if (s_mr_node_key != null)
                                    {
                                        s_nr_node = glee_fsm_graph.FindNode(s_mr_node_key);
                                        s_nr_node.Attr.FillColor = Microsoft.Msagl.Drawing.Color.LightGreen;
                                        Edge edge_s_m = null;
                                        //if (m_ref.transitions.Count() > 0)
                                        //{
                                        //     edge_s_m = new Edge(t_mr_endNode_key, "[ACT-M:" + s_mr.name + "]", s_mr_node_key);
                                        //}
                                        //else
                                        //{
                                        //    edge_s_m = new Edge(t_endNode_final_key, "[ACT-M:" + s_mr.name + "]", s_mr_node_key);
                                        //}

                                        if (m_ref.states.Count() > 0 && t_mr_endNode_key != null)
                                        {
                                            edge_s_m = new Edge(t_mr_endNode_key, "[ACT-M:" + s_mr.name + "]", s_mr_node_key);
                                            edge_s_m.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                            glee_fsm_graph.Edges.Add(edge_s_m);
                                        }
                                        else if (t_mr_endNode_key != null)
                                        {
                                            edge_s_m = new Edge(s_mr_node_key, "[ACT-M:" + s_mr.name + "]", t_endNode_final_key);
                                            edge_s_m.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                            glee_fsm_graph.Edges.Add(edge_s_m);
                                        }
                                        
                                        t_mr_endNode_key = s_mr_node_key;
                                    }
                                }

                                if (m_ref.states.Count() > 0 && m_ref.actions.Count ==0)
                                {
                                    string desc_t_mmu = "ACT-M:[T-S]";
                                    t_mmu_edge = new Edge(t_mr_endNode_key, desc_t_mmu, t_endNode_final_key);
                                    t_mmu_edge.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                    glee_fsm_graph.Edges.Add(t_mmu_edge);
                                }

                                //add mitigation actions

                                for (int i = 0; i < m_ref.actions.Count(); i++)
                                {
                                    PMisuseAn.behaviour.model.Action s_a_mr = m_ref.actions.ElementAt(i);

                                    String s_mr_name = s_a_mr.stateName;
                                    string s_mr_node_key = null;
                                    foreach (DictionaryEntry entry in nodes)
                                    {
                                        Node n = (Node)entry.Value;
                                        if (n.LabelText.Equals(s_mr_name))
                                        {
                                            s_mr_node_key = (string)entry.Key;
                                            break;
                                        }
                                    }
                                    Node s_nr_node = null;
                                    if (s_mr_node_key != null)
                                    {
                                        s_nr_node = glee_fsm_graph.FindNode(s_mr_node_key);
                                        s_nr_node.Attr.FillColor = Microsoft.Msagl.Drawing.Color.LightGreen;
                                        Edge edge_s_m = new Edge(t_mr_endNode_key, "ACT-[M:" + s_mr_name + "]ACT", s_mr_node_key);
                                        edge_s_m.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                        glee_fsm_graph.Edges.Add(edge_s_m);

                                        t_mr_endNode_key = s_mr_node_key;
                                    }
                                }

                                if (m_ref.states.Count() > 0 && m_ref.actions.Count > 0)
                                {
                                    string desc_t_mmu = "ACT-M:[T-S]ACT";
                                    t_mmu_edge = new Edge(t_mr_endNode_key, desc_t_mmu, t_endNode_final_key);
                                    t_mmu_edge.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                    glee_fsm_graph.Edges.Add(t_mmu_edge);
                                }
                            }

                            else
                            {
                                foreach (Edge s_in_edge in _s_in_edges)
                                {
                                    //remove edge from _s_node
                                    glee_fsm_graph.Edges.Remove(s_in_edge);

                                    //get s_in_edge_keys and recreate new edge link to mitigation ref
                                    string s_in_edge_source_key = s_in_edge.SourceNode.Id;
                                    string s_in_edge_target_key = s_in_edge.TargetNode.Id;

                                    string last_t_mr_endNode_key = null;
                                    Edge t_mmu_edge = null;

                                    for (int i = 0; i < ordered_mitigation_trans.Count(); i++)
                                    {
                                        Transition t_mr = ordered_mitigation_trans.ElementAt(i);

                                        foreach (DictionaryEntry entry in nodes)
                                        {
                                            Node n = (Node)entry.Value;

                                            if (n.LabelText.Equals(t_mr.startState))
                                            {
                                                t_mr_sourceNode_key = (string)entry.Key;
                                            }
                                            else if (n.LabelText.Equals(t_mr.endState))
                                            {
                                                t_mr_endNode_key = (string)entry.Key;
                                            }
                                            //if (t_mr_sourceNode_key != null && t_mr_endNode_key != null)
                                            //{
                                            //    break;
                                            //}
                                        }
                                        if (t_mr_sourceNode_key == null)
                                        {
                                            t_mr_sourceNode_key = genNodeID(glee_fsm_graph);
                                            glee_fsm_graph.NodeMap.Add(t_mr_sourceNode_key, t_mr.startState);
                                        }
                                        if (t_mr_endNode_key == null)
                                        {
                                            t_mr_endNode_key = genNodeID(glee_fsm_graph);
                                            glee_fsm_graph.NodeMap.Add(t_mr_endNode_key, t_mr.endState);
                                        }
                                        if (last_t_mr_endNode_key != null)
                                        {
                                            string last_desc_t_mmu_mit = "ACT-T[MIT-LINK]";
                                            Edge last_t_mmu_mit_edge = null;
                                            last_t_mmu_mit_edge = new Edge(last_t_mr_endNode_key, last_desc_t_mmu_mit, t_mr_sourceNode_key);
                                            last_t_mmu_mit_edge.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                            glee_fsm_graph.Edges.Add(last_t_mmu_mit_edge);
                                        }
                                        else
                                        {
                                            string last_desc_t_mmu_mit = "ACT-T[MIT-LINK]";
                                            Edge last_t_mmu_mit_edge = null;
                                            last_t_mmu_mit_edge = new Edge(s_in_edge_source_key, last_desc_t_mmu_mit, t_mr_sourceNode_key);
                                            last_t_mmu_mit_edge.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                            glee_fsm_graph.Edges.Add(last_t_mmu_mit_edge);
                                        }
                                        string desc_t_mmu_mit = t_mr.transitionName + "ACT-[MITIGATED][" + mit_no + "]";
                                        mit_no = mit_no + 1;
                                        Edge t_mmu_mit_edge = null;
                                        t_mmu_mit_edge = new Edge(t_mr_sourceNode_key, desc_t_mmu_mit, t_mr_endNode_key);
                                        t_mmu_mit_edge.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                        glee_fsm_graph.Edges.Add(t_mmu_mit_edge);

                                        last_t_mr_endNode_key = t_mr_endNode_key;

                                    }

                                    if (m_ref.states.Count() == 0 && m_ref.actions.Count() ==0)
                                    {
                                        string final_desc_t_mmu_mit = "ACT-T[MIT-LINK-F]";
                                        mit_no = mit_no + 1;
                                        Edge final_t_mmu_mit_edge = null;
                                        final_t_mmu_mit_edge = new Edge(last_t_mr_endNode_key, final_desc_t_mmu_mit, s_in_edge_target_key);
                                        final_t_mmu_mit_edge.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                        glee_fsm_graph.Edges.Add(final_t_mmu_mit_edge);
                                    }

                                    //add mitigation nodes (mitigation states)
                                    var mitigation_states = new Dictionary<State, int>();
                                    foreach (State state in m_ref.states)
                                    {
                                        mitigation_states.Add(state, state.mitigationSeqRefIndex);
                                    }

                                    var ordered_mitigation_states = from k in mitigation_states.Keys
                                                                    orderby mitigation_states[k] ascending
                                                                    select k;

                                    for (int i = 0; i < ordered_mitigation_states.Count(); i++)
                                    {
                                        State s_mr = ordered_mitigation_states.ElementAt(i);

                                        string s_mr_node_key = null;
                                        foreach (DictionaryEntry entry in nodes)
                                        {
                                            Node n = (Node)entry.Value;
                                            if (n.LabelText.Equals(s_mr.name))
                                            {
                                                s_mr_node_key = (string)entry.Key;
                                                break;
                                            }
                                        }
                                        Node s_nr_node = null;
                                        if (s_mr_node_key != null)
                                        {
                                            s_nr_node = glee_fsm_graph.FindNode(s_mr_node_key);
                                            s_nr_node.Attr.FillColor = Microsoft.Msagl.Drawing.Color.LightGreen;
                                            Edge edge_s_m = new Edge(t_mr_endNode_key, "ACT-[M:" + s_mr.name + "]", s_mr_node_key);
                                            edge_s_m.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                            glee_fsm_graph.Edges.Add(edge_s_m);

                                            t_mr_endNode_key = s_mr_node_key;
                                        }
                                    }
                                    if (m_ref.states.Count() > 0 && m_ref.actions.Count() == 0)
                                    {
                                        string desc_t_mmu = "ACT-M:[T-S]";
                                        t_mmu_edge = new Edge(t_mr_endNode_key, desc_t_mmu, t_endNode_final_key);
                                        t_mmu_edge.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                        glee_fsm_graph.Edges.Add(t_mmu_edge);
                                    }

                                    //add mitigation actions

                                    for (int i = 0; i < m_ref.actions.Count(); i++)
                                    {
                                        PMisuseAn.behaviour.model.Action s_a_mr = m_ref.actions.ElementAt(i);

                                        String s_mr_name = s_a_mr.stateName;
                                        string s_mr_node_key = null;
                                        foreach (DictionaryEntry entry in nodes)
                                        {
                                            Node n = (Node)entry.Value;
                                            if (n.LabelText.Equals(s_mr_name))
                                            {
                                                s_mr_node_key = (string)entry.Key;
                                                break;
                                            }
                                        }
                                        Node s_nr_node = null;
                                        if (s_mr_node_key != null)
                                        {
                                            s_nr_node = glee_fsm_graph.FindNode(s_mr_node_key);
                                            s_nr_node.Attr.FillColor = Microsoft.Msagl.Drawing.Color.LightGreen;
                                            Edge edge_s_m = new Edge(t_mr_endNode_key, "ACT-[M:" + s_mr_name + "]ACT", s_mr_node_key);
                                            edge_s_m.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                            glee_fsm_graph.Edges.Add(edge_s_m);

                                            t_mr_endNode_key = s_mr_node_key;
                                        }
                                    }

                                    if (m_ref.states.Count() > 0 && m_ref.actions.Count>0)
                                    {
                                        string desc_t_mmu = "ACT-M:[T-S]ACT";
                                        t_mmu_edge = new Edge(t_mr_endNode_key, desc_t_mmu, t_endNode_final_key);
                                        t_mmu_edge.Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
                                        glee_fsm_graph.Edges.Add(t_mmu_edge);
                                    }
                                }
                            }

                        }

                    }

                }

            }
                        
            string start_key = "";
            if (startState != null)
            {
                foreach (DictionaryEntry entry in nodes)
                {
                    Node n = (Node)entry.Value;
                    if (n.LabelText.Equals(startState))
                    {
                        start_key = (string)entry.Key;
                        break;
                    }
                }

                Node s_n = glee_fsm_graph.FindNode(start_key);
                if (s_n != null)
                {
                    //s_n.Attr.Fillcolor = Microsoft.Glee.Drawing.Color.Green;
                    s_n.Attr.LineWidth = 5;
                }
            }
            
            //remove nodes with no in or out edges
            List<string> treatedNodeIds = new List<string>();
            for (int i = 0; i <= glee_fsm_graph.NodeMap.Count+1; i++)
            {
                foreach (DictionaryEntry entry in nodes)
                {
                    Node n = (Node)entry.Value;
                    bool contained = false;
                    foreach(string n_s in treatedNodeIds)
                    {
                        if (n_s.Equals(n.Id))
                        {
                            contained = true;
                        }
                    }
                    if(!contained)
                    {
                        treatedNodeIds.Add(n.Id);

                        if (n.InEdges.Count() == 0 && n.OutEdges.Count() == 0 && n.SelfEdges.Count() == 0)
                        {
                            bool valid_empty_node = true;
                            bool do_v = true;

                            State xstate = machine_.getState(n.LabelText);
                            MitigationReferences x_m_refx = MisUseAnObjectsDB.
                                           loadStateMitigationReferencesDB(xstate.name, machineName_, MainWindow.clusterName);
                            if (!x_m_refx.isEmpty)
                            {
                                valid_empty_node = false;
                            }
                            else
                            {

                            X: while (do_v == true)
                                {
                                    foreach (Transition x_trans in machine_.transitions)
                                    {
                                        if (x_trans.isMisusePoint)
                                        {
                                            MitigationReferences x_m_ref = MisUseAnObjectsDB.
                                                loadTransitionMitigationReferencesDB(x_trans.transitionName, machineName_, MainWindow.clusterName);
                                            foreach (State s in x_m_ref.states)
                                            {
                                                if (s.name.Equals(n.LabelText))
                                                {
                                                    valid_empty_node = false;
                                                    do_v = false;
                                                    goto X;
                                                }
                                            }
                                        }
                                    }
                                    foreach (State x_state in machine_.states)
                                    {

                                        if (x_state.isMisusePoint)
                                        {
                                            MitigationReferences x_m_ref = MisUseAnObjectsDB.
                                                loadStateMitigationReferencesDB(x_state.name, machineName_, MainWindow.clusterName);
                                            foreach (State s in x_m_ref.states)
                                            {
                                                if (s.name.Equals(n.LabelText))
                                                {
                                                    valid_empty_node = false;
                                                    do_v = false;
                                                    goto X;
                                                }
                                            }
                                        }
                                        else
                                        {
                                            foreach (PMisuseAn.behaviour.model.Action x_action in x_state.actions)
                                            {
                                                if (x_action.isMisusePoint)
                                                {
                                                    MitigationReferences xa_m_ref = MisUseAnObjectsDB.
                                                loadStateActionMitigationReferencesDB(x_action.name, x_state.name, machineName_, MainWindow.clusterName);
                                                    foreach (State s in xa_m_ref.states)
                                                    {
                                                        if (s.name.Equals(n.LabelText))
                                                        {
                                                            valid_empty_node = false;
                                                            do_v = false;
                                                            goto X;
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }

                                    do_v = false;
                                }
                            }
                            
                            if (valid_empty_node == true)
                            {
                                glee_fsm_graph.NodeMap.Remove(n.Id);
                            }
                            break;
                        }   
                    }
                                    
                }                
            }
                        
            //change font size
            //foreach (Edge node_f in glee_fsm_graph.Edges)
            //{
            //    node_f.Label.FontSize = 16;
            //}
            //for (int i = 0; i <= glee_fsm_graph.NodeMap.Count + 1; i++)
            //{
            //    foreach (DictionaryEntry entry in nodes)
            //    {
            //        Node n = (Node)entry.Value;
            //        n.Label.FontSize = 16;
            //    }

            //}
            //display graph
            viewer.Graph = glee_fsm_graph;            
            viewer.BackColor = System.Drawing.Color.White;
            viewer.Dock = System.Windows.Forms.DockStyle.Fill;

            this.fsm_wfh.Child = viewer;
        }
        
        Graph CreateFSMGraph()
        {
            machine_ = MisUseAnObjectsDB.loadStateMachineDB(machineName_, MainWindow.clusterName);
            startState = MisUseAnObjectsDB.getStartState(machineName_, MainWindow.clusterName);
            endState = MisUseAnObjectsDB.getEndState(machineName_, MainWindow.clusterName);

            // Create an FSM.
            Graph fsm = new Graph();

            foreach (State s in machine_.states)
            {
                Node node = new Node(s.name);
                if (startState != null && s.name.Equals(startState))
                {
                    node.Attr.Shape = Microsoft.Msagl.Drawing.Shape.DoubleCircle;
                    node.Attr.AddStyle(Microsoft.Msagl.Drawing.Style.Rounded);
                }
                else if (endState !=  null && s.name.Equals(endState))
                {
                    node.Attr.Shape = Microsoft.Msagl.Drawing.Shape.Circle;
                    //node.Attr.FillColor = Microsoft.Msagl.Drawing.Color.Gray;
                    node.Attr.AddStyle(Microsoft.Msagl.Drawing.Style.Bold);
                    node.Attr.AddStyle(Microsoft.Msagl.Drawing.Style.Dashed);

                }
                else
                {

                    node.Attr.Shape = Microsoft.Msagl.Drawing.Shape.Circle;
                }
                fsm.AddNode(node);
            }

            foreach (Transition t in machine_.transitions)
            {
                string desc = t.transitionName + "(" + t.associatedEevent + ")";
                fsm.AddEdge(t.startState, desc, t.endState);
            }            
            
            return fsm;
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {

        }

        private void expand_graph_b_Click(object sender, RoutedEventArgs e)
        {
            if (glee_fsm_graph != null)
            {
                ExpandedGraphWindow egw = new ExpandedGraphWindow(glee_fsm_graph);
                egw.Owner = (Window)this.Parent;
                egw.ShowDialog();
            }
        }

    }
}
